Reputation: 545
I'm a little bit confused by the following code
int main()
{
int* a = new int{12};
int* b = new int;
b = a;
delete a;
delete b;
return 0;
}
The code returns an error that
a.out(27538,0x10ade7e00) malloc: *** error for object 0x7f8c18504160: pointer being freed was not allocated
a.out(27538,0x10ade7e00) malloc: *** set a breakpoint in malloc_error_break to debug
zsh: abort ./a.out
My question is that, when I delete the a, does it automatically delete b? What is the mechanism here, I'm a little bit getting lost.
Upvotes: 0
Views: 574
Reputation: 182761
Let's walk through the code line by line.
int* a = new int{12};
This creates a new variable called a
of type int*
and initializes it to point to a newly-allocated integer assigned the value 12.
int* b = new int;
This creates a new variable called b
of type int*
and initializes it to point to a newly-allocated integer.
b = a;
This changes b
's value to point to a
. The value returned in the second call to new
is now lost and that memory is leaked since it is no longer possible to pass it to delete
.
delete a;
This deletes the object a
points to, the one allocated first.
delete b;
Oops, this tries to delete the object b
points to, but b
doesn't point to any object that currently exists. The one allocated first was just deleted and no pointer to the second one exists. So this is a bug.
I suspect you are thinking that delete a;
deletes a
. It does not. It deletes whatever object a
points to and requires that a
be a pointer and point to a valid object that was allocated with new
.
Upvotes: 2
Reputation: 117298
b = a; // here the int that b pointed at "leaks" (you have no way of deleting it)
delete a; // here "a" is deleted first
delete b; // here "a" is deleted a second time (undefined behavior)
When you assign the value of a
to b
, the value (address if you will) b
previously contained, is forgotten. Both a
and b
then points at the same object. You then lost all possibilities to delete
the original object b
pointed at. When you then delete b
you in fact try deleting a
a second time.
Upvotes: 8
Reputation: 238351
When you delete a pointer, all pointers, references, iterators etc. pointing to the destroyed object are invalidated. Because of the assignment b = a
, b points to the same object as a does, so when a is deleted, b becomes invalid. Deleting an invalid pointer has undefined behaviour.
Note that b = a
makes it impossible to delete the allocation that b previously pointed at. This is called a memory leak.
Upvotes: 0