Memory in C – an example

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=[31]   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.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s