Hi,
Can anybody tell me what is the difference memory allocation from stack and heap ?
And how compiler decide from where to allocate the memory to objects and variable ??
Thanks
Hi,
Can anybody tell me what is the difference memory allocation from stack and heap ?
And how compiler decide from where to allocate the memory to objects and variable ??
Thanks
The easy explanation:
The stack is the default place of allocation. Any variables you define reside there. They are cleaned up automatically after a function ends.
The stack is limited (around 1 MB).
The heap is essentially the big memory in the system. It's limited only to the amount of memory you have installed[1]. Objects on the heap are not automatically destroyed, so you need to do so manually (thankfully, smart pointers and RAII can take care of that for us in C++). This is good because it outlives the life of a function.
[1] The heap is actually limited to 2/3 GB depending on OS. The OS will handle where the memory is stored. If you don't have enough physical memory, it will page it to the pagefile.
int i; //stack
int *i = malloc(sizeof(int)); // i is on the stack, *i is on the heap.
Ah yes. What Elysia said.
You could read GotW #9: Memory Management - Part I
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)