They don't contain the same memory space - they contain the same amount of memory. But there is a
big difference.
when you write
int a[10];
You declare an array of ten integers on the stack.
When you write
int *p;
p=new int [10];
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
delete
keyword.
There are two effects of this:
1) If you use
new
without using
delete
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:
int* getP()
{
int a[10];
return &(a[0]);
}
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".
[edit]Typo - "stack" for "heap" - OriginalGriff[/edit]
[edit2]Brain fart - "free" for "delete" - OriginalGriff[/edit2]