int main()
{
int x = 3;
int* y = new int(4);
y = &x;
cout << y;
delete y;
}
it shows the following error:
Error in './a.out':free(): invalid pointer:0x00007ffde8e1c0364
0x7ffde8e1c0364 Aborted
int main()
{
int x = 3;
int* y = new int(4);
y = &x;
cout << y;
delete y;
}
it shows the following error:
Error in './a.out':free(): invalid pointer:0x00007ffde8e1c0364
0x7ffde8e1c0364 Aborted
y cannot be deleted because it points to a an object with automatic storage after the line
y = &x;
Only an address returned by new may be deleted. If the operand of delete has some other value (such as address of an automatic object, as in the example) the behaviour of the program will be undefined.
The quoted assignment overwrites the previous value, which was the only copy of the address of the dynamic allocation. This loss of the address is called a "memory leak", since the dynamic allocation can no longer be released.
delete destroys objects previously allocated by new, but x was not allocated by new. Your code is the same as:
int x=3;
delete &x;
See Also:
I think you need to dereference y and assign to x.
int main()
{
int x = 3;
int* y = new int(4);
*y = x;
cout << y;
delete y;
}
I don't get any core dumps with that.
When you do int x = 3;, x is stored on stack. After y = &x, pointer y points to an element in stack. When you try to delete stack memory, you get a coredump as delete works only on memory allocated on heap.
Because delete auto-storage-class is not a supported use of operator delete.
In the statement, int* y = new int(4);, you use operator new to perform an allocation.
However, in the statement, y = &x;, you change the pointer to auto int x = 3;.
An auto storage class variable is allocated by the C/C++ runtime and never by the user. This is the reason it is an error to try and delete &x;.