1

Is it allowed to use a pointer's name of a pointer once deleted?

This code, for instance, won't compile.

    int hundred = 100;
    int * const finger = &hundred;
    delete finger;

    int * finger = new int; // error: conflicting declaration 'int* finger'

This won't either:

    int hundred = 100;
    int * const finger = &hundred;
    delete finger;

    int finger = 50; // error: conflicting declaration 'int finger'
Mykola Tetiuk
  • 153
  • 1
  • 13
  • 4
    The pointer itself is not deleted, only the thing it is pointing to. So the pointer still exists and you cannot use that name in the same scope for something different. Also please never delete something that you did not create with `new`, this is a crash waiting to happen. – perivesta Feb 03 '21 at 13:43
  • Thank you. Now I get it. – Mykola Tetiuk Feb 03 '21 at 16:16

1 Answers1

2

No. The int * is still an living object. The lifetime of the int that it pointed to has ended.

Note that

int hundred = 100;
int * const finger = &hundred;
delete finger;

has undefined behaviour, as you have attempted to delete an object that was not allocated by new.

In general, new and delete should not appear in C++ programs. Owning pointers should be std::unique_ptr (or rarely std::shared_ptr or other user-defined smart pointer type).

Caleth
  • 52,200
  • 2
  • 44
  • 75