where pointers and global variables in C are saved in memory, in heap or in stack?
views:
73answers:
4Global variables are usually stored in the applications data segment.
Pointers aren't stored any differently than other variables (e.g. if you have a local variable of type int*
, it will be stored on the stack, same as any other local variable).
Global variables can be in a couple places, depending on how they're set up - for example, const
globals may be in a read-only section of the executable. "Normal" globals are in a read-write section of the executable. They're not on the heap or the stack at all. Pointers are just a type of variable, so they can be wherever you want them to be (on the heap if you malloc()
them, on the stack if they're local variables, or in the data section if they're global).
Memory via malloc()
is taken from the heap. This provides a pointer to the memory.
More info here.
Compile
When a file is compiled, variables with "program duration" (static or global variables) which are defined within that "compilation unit" (in rough terms, the "c file") determine how much global space this program needs, and how it is initialized.
Link
When the linker creates your executable, it combines this information and puts it into sections of the executable used for that purpose. The linker then goes through and changes all references to that data to where it will put that data in the process's memory space when the program is loaded. So the pointers to the global data will be like constants in your source file; no memory needs to be set aside for them.
For zero-initialized or uninitialized global data, just the amount of space needed for such data is stored. For initialized data, the initial values are stored.
Load
When your program is loaded, the loader will look into the program file to tell how much zero-initialized data is needs, and sets aside enough of the process's memory space for it, and initializes it all to binary zero. For the initialized data, it sets aside memory for that and initializes it to the initial values saved in the exe file. It also sets aside areas for the heap (used by malloc()) and the stack.
Dynamic Libraries
If your code is in a dynamic library, the linker can't know where it will put the global data. In this case, it creates sections in the library to tell it where the references to the global data are, and the loader takes care of changing the references to point to the right place when it loads the file (this is why you pass -fPIC on the gcc command line for dlls). But since this is done at load time, by the time your program runs the placement of the data is known, so the loader knows where that data will be pointers to global data can still act as constants in your program.
Dynamic Loading
If you link dynamically to a dll, the loader doesn't know about it, so you have to call functions which know how to load a dll and get the address of its exported data and functions.