3 ms·
How does this not segfault on -O0 if the pointer is NULL?
by nothrabannosir 11y ago
How does this not segfault on -O0 if the pointer is NULL?
- jzwinck 11y agoConceptually, dereferencing a pointer then taking the address of the result is a no-op, you get back what you put in. There's no requirement for dereferencing a null pointer to segfault, only an expectation of many modern commodity-system programmers. Some systems allow you to dereference NULL and just return a bunch of zeros there. It's allowed by C and C++. The real question is, how does anyone compile without "-Wall -Werror" in 2015? Ignoring your compiler when it tells you your code is wrong is negligence.
- Kristine1975 11y agoSome systems allow you to dereference NULL For example inside the Linux kernel. GCC has the special switch "-fno-delete-null-pointer-checks" that turns off the assumption that a dereferenced pointer is never null: https://homes.cs.washington.edu/~akcheung/papers/apsys12.html https://homes.cs.washington.edu/~akcheung/papers/apsys12.htm...
- gizmo686 11y agoMy understanding of the C standard is that is explicitly does not allow you to dereference NULL, even if you really want to know what is at memory address 0. Of course this behaviour is only undefined, so an implementation if free to let you do it if it wants to.
- Kristine1975 11y agoMinor nitpick: A NULL pointer need not point to memory address 0 (e.g. it could point to the highest possible address, or have a special "this is a NULL pointer" bit set). The C11 Standard does a little dance with "null pointer" and "null pointer constant" there, c.f. chapter 6.3.2.3: An integer constant expression with the value 0 [...] is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
- Deregibus 11y agoIt's not dereferencing NULL that causes the segfault, its the actual reading or writing of the memory at the invalid address. So, ignoring undefined behavior etc, "* ptr;" doesn't actually generate a load or store since its not really doing anything, but "x = * ptr;" or "* ptr = x;" would. You can also see similar behavior when calling a non-virtual member function on a NULL pointer, the crash doesn't occur until the function actually tries to access some data on "this". This is all with the caveat that the actual behavior depends on the system and compiler as many others have pointed out.
- deleted 11y ago[deleted]
- saurik 11y agoIn C++, dereferencing a pointer doesn't give you a value: it gives you a "reference". While a compiler is possibly allowed to do so, I would be shocked to the point of saying "this compiler doesn't work" at a compiler that actually went out of its way, even with optimizations turned off (as this isn't an optimization issue), to access the memory at the address of the pointer in any way if the reference was never actually used.