Click here to Skip to main content
15,922,407 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
I want to know if heap is used for holding local variables during function calls. Thank you.
Updated 3-Jun-10 7:04am

Global variables are stored on the heap and local variables are stored on the stack.

Objects created by the new keyword are stored on the heap because they will stay their for an indefinite time.

Pointer created in a function are stored on the stack while the objects or memory blocks they point to might be stored on either the heap or the stack. e.g.
int a = 5;
int *b = &a;

'b' is stored on the stack and points to an object on the stack. While
int *a = new int[6];

'a' is stored on the stack while the array it points to is stored on the heap.
Share this answer
In addition to CcoollzZ's answer, you can refer to this[^] for a detailed explanation on the subject.
Also have a look at this[^] thread. :)
Share this answer
The stack is used when you do not use new or malloc or other related memory allocation functions explicitly.

For example:

int x;//<--- stack space is used.

int *x = new int();//<--- heap space is used. 

Relating to function calls, the function call, and the parameters passed in, and the variables declared inside the function are all on the stack unless you explicitly allocate them on the heap.

void myFunc(int x)
  int y;//<--- allocated on the stack

Anything allocated on the heap must be freed. For C allocations use free, for C++ allocations use delete or delete[] for arrays.

You can also find my answer here which gives a lot more differences between the stack and the heap.
Share this answer
With all the compilers I've used the heap isn't used for holding local variables, either when they're defined or passed to functions.

HOWEVER there's no reason why a compiler internally couldn't generate code to do this if it didn't change the observable behaviour of the program.

And don't be fooled that because something is declared as a local variable it automatically ends up on the stack. Compiler optimisers are quite good at sticking stuff in registers and other tricks that make it difficult to determine what's going where.

Basically don't assume anything about where a variable is stored and you'll be okay. Unless you're writing something like a garbage collector in which case you have to care but that's not something ordinary mortals like me would consider doing.


Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900