Was That Pointer Allocated "On the Heap" or "On The Stack?"

The answer to this very rudimentary C/C++ 101 terminology question is buried somewhere in my class notes, which in turn are buried somewhere in a packing box, but is nowhere to be found on the Web nor in my textbooks. There are two ways to create a pointer-- which one is the 'heap' and which one is the 'stack' flavor'?

Well, I pestered my local expert programmer and he refreshed my memory (as opposed to reallocated it) on the difference.
The difference is:

Allocate on the Heap:

pMyPointer = new Stuff*;

Remember that when you 'new' a pointer, when you are done with it you will have to 'delete' it.
(In C the equivalent functions are 'malloc' and 'dealloc'.)
Otherwise the block of memory your pointer used to point to will be "orphaned" upon destruction of the pointer. It will still be allocated, but the system won't be able to get to it. Do this enough times and all of your system's memory will be choked with unusable, unreachable spoken-for memory and it will crash. So always be sure to:

delete pMyPointer; // deallocates the memory it pointed to
pMyPointer = NULL; // makes sure the pointer no longer points to the now-invalid memory

Allocate on the Stack:

Stuff* pMyPointer; // create the pointer
pMyPointer = &SomeStuff; // point it to some data

The memory this pointer points to was already created elsewhere and is still accessible from elsewhere. The pointer was created "after the fact" and if it is destroyed, it does not leave the memory orphaned.

Thanks to Nadeem Khan of Hewlett-Packard Company for straightening this out.

Back to Crocuta Main