diff --git a/clang.md b/clang.md index 4b6ef33f741c0273882688853246cafb53a0ee8a..2dbfd0e1eb89256ebe69cbd8be1050af9a86b65e 100644 --- a/clang.md +++ b/clang.md @@ -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: + + + +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. diff --git a/images/program-address-space.png b/images/program-address-space.png new file mode 100644 index 0000000000000000000000000000000000000000..76cf8fcfc1800c5901824490441f72f1383b21da Binary files /dev/null and b/images/program-address-space.png differ