The C language does not determine where any variables are stored. However, it defines three storage classes: static, automatic, and dynamic.
Static variables are created during program initialization (before main()
) and remain in effect until the program terminates. A scope object ("global") and static variables are categorized. Although they are usually stored in a data segment, the C standard does not require this to be the case, and in some cases (for example, C interpreters) they can be stored in other places, such as a heap.
Automatic variables are local variables declared in the function body. They are created when the program flow reaches its announcement and is destroyed when they go out of scope; new instances of these variables are created for recursive function calls. The stack is a convenient way to implement these variables, but again, this is not required. You could also implement automation on the heap if you selected, and they are usually placed in registers. In many cases, an automatic variable will move between the stack and the heap during its lifetime.
Note that the register
annotation for automatic variables is a hint - the compiler does not have to do anything with it, and indeed many modern compilers completely ignore it.
Finally, dynamic objects (in C there is no such thing as a dynamic variable) refer to values created explicitly using malloc
, calloc
or other similar distribution functions. They arise upon explicit creation and are destroyed upon explicit liberation. A heap is a convenient place to place them, or rather, defines a heap based on the ability to make this distribution style. But then again, a compiler implementation can do whatever it wants. If the compiler can perform static analysis to determine the lifetime of a dynamic object, it can transfer it to a segment or data stack (however, some C compilers do this “escape analysis”).
The key conclusion here is that the C language standard only defines the lifetime of a given value. And the minimum boundary for this lifetime is that it can remain longer than required. Exactly how to place this in memory is a subject in which linguistic and library implementation gains significant freedom.
source share