-5
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

Ron
  • 14,674
  • 4
  • 34
  • 47
Amit Kumar
  • 49
  • 1
  • 9

5 Answers5

9

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
6

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:

Doug Richardson
  • 10,483
  • 6
  • 51
  • 77
2

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.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
JimNastic
  • 39
  • 4
  • 4
    This is not wrong, but I don't believe it answers the question (**Why** delete cannot be called on the pointer.) – Ben Jones Aug 28 '19 at 16:19
  • 5
    In addition to the above, minor nitpick: "_I don't get any core dumps with that._" If you don't get core dump with a specific piece of code, in several executions, of it, it doesn't, automatically, prove, that the code is free of undefined behavior. – Algirdas Preidžius Aug 28 '19 at 16:25
  • @BenJones Is it because 'y' is assigned a value equal to the address of 'x' ? – JimNastic Aug 28 '19 at 20:18
  • assigning the address `&x` to the pointer `y` is perfectly valid. The issue is that [you cannot `delete` an object allocated on the stack](https://stackoverflow.com/questions/441831/calling-delete-on-variable-allocated-on-the-stack). – Ben Jones Aug 29 '19 at 15:42
0

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.

0

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;.

C. R. Ward
  • 93
  • 5