There are 3 different kinds of storage duration in C language:
- static: the lifetime of the variable is the lifetime of the program. It is allocated at load time (only defined at compile time) and only freed when the operation system unloads the program. Static variables are variables declared outside any functions, and local variables (declared in a function or block) having the
static
modifier
- automatic: automatic variables are declared inside a block (or function), with no storage modifier. Their lifetime starts at the beginning of the bloc and ends at the end of the bloc. They are generally allocated at the beginning of the bloc and deallocated at its end, but because of the as if rule, optimizing compilers could allocate them sooner and free them later, for example if the bloc in located inside a loop.
- dynamic: they are allocated manually through
malloc
, and will only be deallocated by free
Common implementations use a system stack for automatic variables and a memory pool (asking the Operating System when more memory is needed) for dynamic ones, but this is an implementation details
When multithreading is used, a fourth kind of storage duration is available: thread storage duration. Those variable are declared with the _Thread_local
storage class modifier. Their lifetime is the duration of the thread, and each thread has its own copy of them.
For common implementation, they are managed the same as static variables: they are allocated by the operating system when the thread is created, and reclaimed (still by OS) when the thread ends.
Some remarks regarding your wordings:
Static memory allocation - this happens during compile time.
Beware, compile time and load time are different. At build time only a file is created, and memory is only allocated by the system at run time
Static memory deallocation - the memory is deallocated automatically when the block/function is finished running (for local variables)...
There is a confusion between scope (local vs. global) and storage duration. A function can contain static variables, that is one of the reasons for the static
keyword
Dynamic memory allocation - the memory is allocated during run-time because the size of the input is unknown at this time
This is one possible reason for the programmer to use dynamic memory, but there might be others, for example because the code would be cleaner that way. In particular, dynamic memory is a nice tool when you want to mimic Object Oriented Programming in C language.