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.
aandbpoint to the same memory. Deleting both causes you to delete the same memory block 2 times which is undefined behavior. You also leaked the memory thatboriginally pointed to. There is no way to delete that because the address was thrown away in theb = a;assignment.new, bothaandbhave different values. It is those values that matter, not the name. When you issued thedeletecall, you are deleting the same value twice since you assigned the value ofatob.