Memories of C

C has three different pools of memory.

Static: global variable storage, permanent for the entire run of the program.
Stack: local variable storage (continuous memory).
Heap: dynamic storage (large pool of memory, not allocated in contiguous order).

For example:

int theforce;

On an Intel Core Duo, the variable uses 4 bytes of memory. This memory can come from one of two places. If a variable is declared outside of a function, it is considered global, meaning it is accessible anywhere in the program. Global variables are static, and there is only one copy for the entire program.

The stack is used to store variables used on the inside of a function. Once a function finishes running, all the memory it uses is freed up. The stack is a special region of memory. Stack memory is divided into successive frames where each time a function is called, it allocates itself a fresh stack frame.

The heap is a bunch of memory that can be used dynamically. The heap is generally used by dynamic allocator functions such as malloc. If you want 4kb of memory for an object the dynamic allocator will obtain it from the heap.

Consider the following example:

	#include <stdio.h>
	#include <stdlib.h>

	int x;          

	int main(void) 
	{
	    int y;   
	    char *str; 
  
	    str = malloc(100);  
	    free(str);          

	    return 0;
	}

The variable x is static storage, because of its global nature. Both y and str are dynamic stack storage which is deallocated when the program ends. The function malloc is used to allocate 100 bytes of dynamic heap storage to str. Conversely, the function free, deallocates the memory associated with str.

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