So what actually happens when memory is used in a program? The executable file that a C compiler creates contains the following information (say the generic a.out):
- a.out magic number
- other a.out contents
- size needed for BSS (Better Save Space) segment
- data segment (initialized global and static variables)
- text segment (executable instructions)
Local variables don’t go into a.out, they are created at runtime, and stored in the stack. When an executable, such as a.out, is run, the parts of the program are put into memory. Memory space for items such as local variables, parameter passing in function calls, etc. is created in a stack segment, often called the runtime stack, and heap space is allocated for dynamically allocated memory. The stack provides a storage area for local variables. The stack stores the “housekeeping” information associated with function calls, known as a stack frame, and works as a scratch-pad area for temporary storage.
On many systems the stack grows automatically as more space is needed. When all the space in the stack has been used up, stack overflow occurs. Consider the follow examples of variables declared in a function:
char str="Do or do not, there is no try!"; char *s="I am the master!"; int x;
In the stack region of memory, the following data is stored:
Name Type Value str array of char, size= Do or do not, there is no try!\0 s pointer (to char) 00E9 x int
In the heap region of memory, the following data is stored:
Type Address Value string literal 00E9 I am the master!\0
In the case of str, it has a size implicitly set at 31 (for the 30 characters enclosed in double quotes, and the \0 terminating character). str has memory reserved for it in the stack. The pointer variable s is declared to hold the address (00E9) of the first character of the string. The string is stored in the heap region of memory, not the stack.