memory allocation in Stack and Heap

Samir Baid picture Samir Baid · Jul 21, 2011 · Viewed 50.7k times · Source

This may seem like a very basic question, but its been in my head so:

When we allocate a local variable, it goes into stack. Similarly dynamic allocation cause the variable to go on heap. Now, my question is, is this variable actually lie on stack or heap or we will just a reference in the stack and Heap.

For example,

Suppose I declare a variable int i. Now this i is allocated on the stack. So, when I print the address of i, this will be one of the location on stack? Same question for heap as well.

Answer

Chris Eberle picture Chris Eberle · Jul 21, 2011

I'm not entirely sure what you're asking, but I'll try my best to answer.

The following declares a variable i on the stack:

int i;

When I ask for an address using &i I get the actual location on the stack.

When I allocate something dynamically using malloc, there are actually TWO pieces of data being stored. The dynamic memory is allocated on the heap, and the pointer itself is allocated on the stack. So in this code:

int* j = malloc(sizeof(int));

This is allocating space on the heap for an integer. It's also allocating space on the stack for a pointer (j). The variable j's value is set to the address returned by malloc.