[prog] guide to memory in C, the stack, heap?

Tim King timk at jtse.com
Fri Feb 17 02:14:22 EST 2006

Angelina Carlton <brat at magma.ca> wrote:

>My C book barely touches on the stack and the heap and what really goes
>on during function calls like malloc and free.
Hi, Angelina. A stack is like a stack of papers. You can put a new sheet 
on top, but you also have to unstack them from the top. This is called a 
last-in-first-out data structure (LIFO), because the last thing you 
"push" on the stack is the first thing to "pop" off.

Each thread in your program has a stack. The C compiler handles it for 
you, and you don't actually have to think about it. The compiler uses 
this stack to save actual parameters and automatic variables. When it 
calls a function, the CPU pushes the actual parameters onto the stack 
and then executes the code inside the function. Then this code allocates 
enough extra space on the stack for automatic variables. As functions 
call other functions, each successive layer pushes more stuff on the 
stack. As each function returns, its stuff gets popped off the stack. 
When you return from the top layer, which would usually be the thread's 
start function, the stack is empty.

The heap is memory you can allocate, use, and then free. It's more like 
a filing cabinet with file folders, some empty and some used. When you 
call malloc, it finds an empty space big enough to hold what you want to 
put in it. When you call free, anything you'd stored in that memory gets 
dumped. That space is then available for future calls to malloc.

Try the following for more info:


Hope this helps.

be the story  http://bethestory.com/
Feeling the Romance and Keeping it Real
Spotlight: City Lights
plus: Sin and Vengeance, Of Stories And Wine

More information about the Programming mailing list