westiti
westiti

Reputation: 35

Double delete two allocated variables in c++

I got this code:

int **a;
int *b;

b = new int;
a = new int*;

*b=10;
a =&b;

std::cout << **a << std::endl;// display 10

If I do this:

delete a;

Do I delete "b" also?

Upvotes: 1

Views: 315

Answers (5)

Thomas Matthews
Thomas Matthews

Reputation: 57729

Rephrasing your question and the code:

int * b = new int;  // Dynamically allocate for 1 integer.
int * * a = new int *; // Allocate 1 pointer dynamically.

// The tricky part to understand.
// The variable `a` points to a pointer.
// So dereferencing 'a' results in a pointer to an integer.
// So, assign the pointer, in dynamic memory, with the content
// of the 'b' pointer.
*a = b;

// What does this statement do?
delete a;

In the above example, the delete frees up the memory allocated for the a variable. Nothing more, nothing less.

The pointer, b, is not effected. It still points to memory allocated for an integer.

The deallocation of memory for a does not affect b because the deallocation function does not operate on the content of allocated memory.

Upvotes: 0

eweb
eweb

Reputation: 749

b is dynamically allocated (b = new int;) then we store 10 into the allocated int.

We then allocate 'a' a pointer to a pointer to int. But then assign to 'a' which means we lose what 'a' was pointing at. When we delete a I guess you'll get an error because it is no longer pointing at dynamically allocated memory.

perhaps you meant *a = b

in which case you would still have to delete a and delete b

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613332

delete a;

Since a was not allocated with new, this results in undefined behaviour.

The problems really start when you assign to a for a second time.

b = new int;
a = new int*;
*b = 10;
a = &b; // oops

At this point you've lost track of the object allocated by the original call to new, that you originally stored in a. So that's a memory leak.

Your code should probably look like this:

int *b = new int;
*b = 10;
int **a = &b;
std::cout << **a << std::endl;
delete b;

Upvotes: 5

kwierman
kwierman

Reputation: 461

Yes. Well, it deletes the object pointed at by b. a and b will still have the value of the address of the original object. In order to make sure that a and b are not used improperly, try adding this:

a=NULL;
b=NULL;

Upvotes: -3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

If you do delete a you tear a hole in the fabric of the universe, because a no longer points to that new int*, but to b, which was not dynamically allocated.

Upvotes: 4

Related Questions