-2

I have a problem deleting a pointer in my code.

This is code:

int *x=new int; 

int a=5;

x=&a;

cout << *x << endl;
delete x;
cout << *x;

Why don't you delete the pointer and print the second cout quietly?

xvmir
  • 11
  • If you delete the pointer how can you access that location? Therefore the second ```cout << *x;``` will throw an error invalid access! – anirudh Apr 29 '21 at 08:47
  • 1
    Does this answer your question? [Deleting a pointer in C++](https://stackoverflow.com/questions/13223399/deleting-a-pointer-in-c) –  Apr 29 '21 at 08:50
  • 1
    Your `delete x;` line is invalid - you have reassigned a different value to the pointer (the address of `a`) *after* the `new` line, so you have lost the address returned by that allocation. – Adrian Mole Apr 29 '21 at 08:50
  • 4
    `delete` does not delete a pointer, it deletes the object that the pointer points to, and that object must have been created with `new`. After you said `x = &a`, `x` no longer points to such an object but to an object with automatic storage, and passing such a pointer to `delete` has undefined behaviour. – molbdnilo Apr 29 '21 at 08:52

1 Answers1

0

Your code has several issues, for this reason it won't work.

First, the delete operator does not delete the pointer itself, but it deallocates what the pointer variable is pointing to. In other words,

int* p = new int();
cout << *p << endl; // this prints 0
cout << p << endl; // this prints 0x84544550 on my machine

you can see from the example above the difference: p is the value of the pointer, pointing on my machine to the memory address 0x84544550, while *p indicates to go to the offset 0x84544550 and read an integer value (4 bytes) from there. The value is 0 as per the `new() operator'.

Then, the moment you perform

x=&a;

you are changing the pointer value (0x84544550 in my case) to the address of a local variable: now, the disaster is that you are thinking to reference something you have previously allocated, but truly is something that you haven't.

The subsequent delete x call will only try to deallocate that memory and not your original int variable.

You must be careful when you assign pointers, as you should preserve the semantics, otherwise you'll end up in nasty bugs.

Have a look at a much more comprehensive explanation: Deleting a pointer in C++

Yennefer
  • 5,194
  • 7
  • 30
  • 42