Hasan H
Hasan H

Reputation: 141

C++ delete pointer allocated twice

I am trying to understand more about c++ pointers and freeing memory. Let's say we have the following piece of code

int main{

  int * A = new int[4];
  int * B = new int[4];
  A = B;

  delete[] A;
  delete[] B;

  return 0;
}

A is pointing to a new created pointer, whereas B is pointing to another one,so we have a total of two pointers. Now saying A = B means that A and B are now pointing to the same pointer. Therefore what happens to the other pointer in this case? And how can we delete it?

Upvotes: 0

Views: 124

Answers (2)

Pete Becker
Pete Becker

Reputation: 76235

There's nothing special about pointers here.

int i = 3;
i = 4;

What happened to the 3? It's gone, overwritten by i = 4. Same thing with pointers:

int *p = new int[4];
int *q = new int[4];

p points at an array of int and q points at another array of int.

p = q;

The old value of p is gone, overwritten by p = q. p and q now hold the same pointer value, and that pointer points at the memory allocated by the second call to new int[4].

To free the memory allocated in the first call to new int[4] you have to hold on to the pointer that new returned.

Upvotes: 3

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

Therefore what happens to the other pointer in this case?

It is lost. You dropped the last reference to the array A was pointing to (A and B are not pointing to pointers. They are pointers and they do point at the first element of the arrays, ie ints, respectively).

And how can we delete it?

You cannot. The memory is leaked.

Don't ever use raw owning pointers. For dynamic arrays you can use std::vector and for others you can use smart pointers. With std::vector your code would be:

#include <vector>
int main{
    auto A = std::vector<int>(4);
    auto B = std::vector<int>(4);
    A = B;
}

And for the sake of completeness also a leak-free version of your code:

void please_dont_do_this() {    
  int * A = new int[4];
  int * B = new int[4];

  delete [] A; // delete the array before the pointer is lost

  A = B;

  delete[] B;  // delete the array only once !    
}

PS: I know this view isnt very popular among enthusiastic beginners who want to learn as much as possible, but imho the most important thing you need to know about raw pointers in C++ is that you almost never need them (and when you think you need them then most likely you still don't).

Upvotes: 4

Related Questions