Use the "new" same pointer several times

What happens when I do something like

int * ptr = new int; *ptr = 5; // ... do some stuff here ptr = new int; // ... reuse ptr to do some other stuff 

Unlike

  int * ptr1 = new int; *ptr1 = 5; // ... do some stuff here delete ptr1; int * ptr2 = new int; // ... use ptr2 now 

????

Does the same thing happen at the hardware level? In other words, in the first case ptr = new int; moves from the previous pointer / value pair and what happens to these old values? Are they replaced, are they just swimming somewhere, etc.?

+5
source share
2 answers

Your int *ptr is just a variable that stores the address, nothing more.

After the first int * ptr = new int; it contains the address of the dynamically allocated integer. After the second int * ptr = new int; it contains the address of another dynamically allocated integer.

What happens is then nothing special, the only thing you did not call delete , so the memory allocated for the first integer will never be freed. There is nothing to track, its address is not stored anywhere, and therefore it will remain useless allocated space until the program ends.

+9
source

In the first example, the pointer is overwritten, but the object it points to still exists and “floats” somewhere. This causes a memory leak .

If this happens in a frequently used function or in a loop, you can easily run out of memory by storing values ​​that you cannot and cannot receive anymore.

Leakage is actually a very common mistake. A good practice is to avoid this using smart pointers like shared_ptr . They track the amount of use and automatically free the object if it is no longer in use. For instance:

  shared_ptr<int> ptr = make_shared<int>(); // allocate an int *ptr = 5; // ... do some stuff here ptr = make_shared<int>(); // the old object is no longer used so deleted automatically // ... reuse ptr to do some other stuff 
+7
source

All Articles