They don't contain the same memory space - they contain the same amount of memory. But there is a big
when you write
You declare an array of ten integers on the stack.
When you write
p=new int ;
You declare the same amount of space, but this time on the heap.
The difference is important: stack space is reclaimed when the function the memory was allocated in returns: the memory goes out of scope, and is automatically released. Heap space does not, it has to be explicitly released by the
There are two effects of this:
1) If you use
then your application consumes more and more memory, which it never lets go - eventually your machine runs out of memory and crashes. This is called a "memory leak".
2) Worse, if you allocate memory on the stack, and then pass that address outside the function, then memory is valid, but may be released:
Is valid code, but the memory that is returned will be reused by the next function you call, so the same memory will be used for two purposes. This is called a "hanging reference" and can cause horribly intermittent faults, or an old-fashioned "general protection fault".
Typo - "stack" for "heap" - OriginalGriff[/edit]
[edit2]Brain fart - "free" for "delete" - OriginalGriff[/edit2]