C++ - Allocating memory on heap using "new"

Simplicity picture Simplicity · Jan 29, 2011 · Viewed 8.1k times · Source

If I have the following statement:

int *x = new int;

In this case, I have allocated memory on the heap dynamically. In other words, I now have a reserved memory address for an int object.

Say after that that I made the following:

delete x;

Which means that I freed up the memory address on the heap.

Say after that I did the following again:

int *x = new int;

Will x point to the same old memory address it pointed to at the heap before it was deleted?

What if I did this before delete:

x = NULL;

And, then did this:

int *x = new int;

Will x point to a a memory address on the heap other than the old one?

Thanks.

Answer

Jerry Coffin picture Jerry Coffin · Jan 29, 2011

In the first case, you might get the same block of memory again, but there's no certainty of it.

In the second case, since you haven't freed the memory, there's a near-certainty that you'll get a different block of memory at a different address. There are garbage collectors of C++. If you used one of these, it's conceivable that the garbage collector would run between the time you NULLed out the pointer (so you no longer had access to the previously-allocated memory block) and asking for an allocation again. In such a case, you could get the same memory block again. Of course, without a garbage collector, you're just leaking memory, so you don't way to do this in any case.