Skip to content
Snippets Groups Projects
Commit bcfdfeb0 authored by Mactavish's avatar Mactavish
Browse files

add storage duration

parent 9a9f3a95
No related branches found
No related tags found
No related merge requests found
......@@ -325,6 +325,65 @@ char str* = "string literal"; // can not be modified via array subscript
## C Memory Management
Memory can be viewed as an array of consecutively addressed memory cells. Typical size of each size is 1 `byte`. A char takes one byte whereas other types use multiple cells depending on there size.
### Program Address Space
The figure below depicts the classical address space of a program:
![](./images/program-address-space.png)
There a typically 4 regions:
- **Stack**: local variables inside functions, grows downwards
- **Heap**: space requested for dynamic data via `malloc()`, resizes dynamically, grows upwards
- **Static data**: variables declared outside functions, does not grow or shrink. Loaded when program starts, can be modified
- **code**: loaded when program starts, does not change
- `0x0000 0000` is reserved and unwriteable/unreadable, so the program crashes on null pointer access.
### Storage Duration
Objects have a storage duration that determines their lifetime. There are **four** storage duration available in C: `automatic`, `static`, `thread`, `allocated`. We won't cover `thread` storage duration here.
#### Automatic
Basically anything you declared within a block or a function has `automatic` storage, which means their lifetimes begins when the block in which they're declared begins execution, and ends when execution of the block ends.
If the block is entered recursively, new objects will be created each time and have their own storage.
#### Static
Objects declared in file scope have `static` storage duration. The lifetime of these objects is the entire duration of the program and their stored value is initialized only once prior to `main` function.
#### Allocated
`Allocated` storage is allocated and deallocated through library functions on requests, using dynamic memory allocation functions.
A concrete example of these storage durations:
```c
#include <stdio.h>
#include <stdlib.h>
/* static storage duration */
int A;
int main(void)
{
printf("&A = %p\n", (void*)&A);
/* automatic storage duration */
int A = 1; // hides global A
printf("&A = %p\n", (void*)&A);
/* allocated storage duration */
int *ptr_1 = malloc(sizeof(int)); /* start allocated storage duration */
printf("address of int in allocated memory = %p\n", (void*)ptr_1);
free(ptr_1); /* stop allocated storage duration */
}
```
## C Compilation Process
Unlike other interpreted programming languages, we use compilers to compile C written programs.
......
images/program-address-space.png

22 KiB

0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment