Hillary Rodham Clinton
Hillary Rodham Clinton

Reputation: 119

Using "new" multiple times on the same pointer

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

as opposed to

   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, does ptr = new int; move on from its previous pointer/value pair, and what happens to those old values? Do they get replaced, do they just float around somewhere, etc.?

Upvotes: 7

Views: 4218

Answers (2)

Christophe
Christophe

Reputation: 73456

In the first example, the pointer is overwritten, but the object it pointed to still exists and is "floating around" somewhere. This causes memory leaking.

If this happens in a frequently used function or in a loop, you could easily exhaust your memory, storing values that you can't nor won't access any more.

Leaking is in fact a very common error. A good practice is to avoid it by using smart pointers such as shared_ptr. These keep track of a usage count, and free the object automatically if it's no longer used. For example:

 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    

Upvotes: 7

coyotte508
coyotte508

Reputation: 9725

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

After your first int * ptr = new int;, it contains the address to a dynamically allocated integer. After your second int * ptr = new int;, it contains the address to another dynamically allocated integer.

What happens then is nothing special, the only thing is that you didn't call delete so the memory allocated for the first integer will never be freed. There's nothing to keep track of it, its address isn't stored anywhere, and so it will keep being useless allocated space until the program ends.

Upvotes: 10

Related Questions