Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 996
Simplicity Avatar asked Jan 29 '11 09:01

Simplicity


2 Answers

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.

like image 143
Jerry Coffin Avatar answered Sep 23 '22 02:09

Jerry Coffin


What you are asking is entirely undefined (as per C/C++ standard) and would depend on the implementation.

it should be easy for you to test this out with your version of the compiler.

What you should note though is to never depend on the outcome of this behavior as it can change any time / with any os / even an upgrade to your compiler.

As to what i think might happen, you would get the same address most likely, UNLESS you have other threads in your program which are also allocating during the same time. But even then you might get the same address, if the particular malloc implementation of your compiler decides to use different heaps for different threads (which is better in terms of perf)

like image 20
computinglife Avatar answered Sep 27 '22 02:09

computinglife