Search code examples
c++memory-managementdangling-pointer

Why is assigning 0 to a pointer a solution to a dangling pointer?


What does the OS/Debugger do when a pointer is assigned 0?


Solution

  • The essential problem this solves is that not all CPU's implement the same sorts of memory dereference semantics. In some cases, it's not possible to make dereferencing an address after it has been free() into anything that looks like an error. This is especially true on embedded processors. In other cases, allocators may be very lazy about returning freed memory to the host operating system, for performance reasons.

    Fundamentally, dereferencing such a pointer could lead to actually seeing the freed region, seeing a zeroed out region, seeing memory that has been returned by a subsequent allocation, or causing a cpu exception. Since such an eventuality is completely reasonable, c++ has assigned this condition as "undefined behavior".

    To get out of that situation, you want to have a way of distinguishing pointer values which have been freed or allocated. As such, C++ requires that dereferencing a pointer that has been assigned 0 is an error, and converting such a pointer to an integer also return zero.


    re: your current edit.

    pointers don't exist for the purposes of operating systems. At the lowest level, there are no strings, integers, floats or pointers of any sort. only bytes. When you write a c++ program that assigns 0 to a pointer value, the operating system simply doesn't enter into the equation. that's totally up to the compiler implementation.

    On the other hand, when you dereference such a pointer in your program, c++ requires that this is be a runtime error. On embedded systems, that's basically not practical, 0 is a perfectly valid memory address on such systems, usually the SRAM is near that address. If the compiler strictly implements the standard, it might insert a check before every dereference to see if it was null, and put the MCU in an error state, but that's unusual, since it would slow an already slow system and increase program size.

    On more fully featured systems, those that have a memory management unit, the zero address in the application is usually not mapped to any physical page, so the operating system does help you here, by raising a segfault in the page program when it tries to access the null pointer value.