Search code examples
c++pointersmemorynull

nullptr & delete (C++)


I do not know the exact mechanism of nullptr and delete keyword.

*1

type* var=new type;
var=nullptr;

*2

type* var=new type;
delete var;

I know *1 and *2 are different but not how do they work exactly.

*1, *2 memory related... IDK jst wnna know difference. And when can use nullptr & delete keyword. Mixing these is impossible?


Solution

  • my_type *ptr = new my_type;
    ptr = nullptr;
    

    After the first line, ptr points at an object of type my_type that was allocated on the free store. After the second line, ptr points at nothing valid. The my_type object on the free store still exists, but there is nothing in this code that can get at it, because the original pointer has been overwritten with a null pointer. This is called a "memory leak".

    my_type *ptr = new my_type;
    delete ptr;
    

    Now, after the second line, the my_type object that was allocated on the free store has been destroyed (i.e., its destructor has been run) and the memory that it occupied has been freed up so that it can be used later in a subsequent call to new. The value in ptr is still the old pointer value, but because of the delete it no longer points at anything useful. This is called a "dangling pointer".

    There's nothing inherently bad about a dangling pointer; if delete ptr; was the last line in a function, when the function returned ptr would no longer exist, so there would be no danger of trying to access the my_type object that no longer exists.

    But sometimes it isn't so easy, and it may be appropriate to mark ptr as not pointing at a valid object by setting it to a null pointer:

    my_type *ptr = new my_type;
    delete ptr;
    ptr = nullptr;
    

    Now, if you need to check it, you can say

    if (ptr)
      // do something with the thing that ptr points at