We set pointers to NULL (0) to avoid dangling pointers (the pointer still points to the same memory that no longer belongs to you). In the case of local variables, this is not so useful if the function does not continue after deletion (therefore, its obvious pointer will not be reused). In case global / participants can use their good practice to avoid mistakes.
Accessing an already deleted pointer can overwrite / read random memory (this can be more dangerous than a crash) and causes undefined behavior , while accessing the NULL pointer will immediately fail.
Since C ++ 11 , you should use nullptr , because its type is a pointer type, and NULL larger than int , and improves type safety + eliminates ambiguous situations.
If you delete the pointer nullptr , it is safe to use delete on nullptr , and nothing happens, but if you delete the already deleted non-zero pointer, it will cause undefined and, most likely, the program will crash.
In C ++, you should avoid using pure pointers, as they are STL containers (which release their resources themselves ( RAII )) for that use or smart pointers .
std::vector<int> array{1,2,3,4,5};
Filip koΔica
source share