Assuming this is C++, your first snippet is equivalent to
C1 *p = new C1(2);
C1 g = *p;
delete &g;
p
is a pointer and lies on the stack.
The location p
points to lies on the heap.
g
is a C1
and lies on the stack.
&g
(the value passed to delete
) therefore returns a memory address from somewhere in the stack segment.
Now, if I'm not mistaken:
Variables on the stack are allocated and deallocated automatically, so while your delete &g
is not itself causing the error, it is the automatic deallocation at the end of the function that triggers it.
Also, g
is a copy of the value pointed to by p
, and not a reference to it or something.
Plus p
does not get deallocated at all.
Now, in your second snippet:
C1 *g = new C1(2);
delete g;
g
is a pointer and lies on the stack.
The location pointed to by g
lies on the heap.
g
(the value passed to delete
) therefore returns a memory address from somewhere in the heap segment, and everyone is happy.