Nullity can be part of the function contract. One approach is to document that "argument must never be null," and leave it at that. More pragmatically, my approach (as a library author) is always to check parameters in the "public API," and assert-fail in debug/development builds. For internal functions, I lean towards checking on the caller side only, but that's not set in stone. The bottom line, though, is that someone needs to be checking. Answer from sgndave on reddit.com
🌐
Reddit
reddit.com › r/c_programming › should you always protect against null pointer dereference?
r/C_Programming on Reddit: Should you always protect against NULL pointer dereference?
December 3, 2024 -

Say, you have a function which takes one or multiple pointers as parameters. Do you have to always check if they aren't NULL before doing operations on them?

I find this a bit tedious to do but I don't know whether it's a best practice or not.

🌐
Reddit
reddit.com › r/cpp_questions › dereferencing null pointers - what does the standard say?
r/cpp_questions on Reddit: Dereferencing null pointers - what does the standard say?
April 20, 2021 -
01: #include <iostream>
02: 
03: class greeter
04: {
05: public:
06:     void hello()
07:     {
08:     std::cout << "Hello world";
09:     }
10: };
11: 
12: int main()
13: {
14:     ((greeter*)nullptr)->hello();
15: }

runs with no warnings on -Weveryting -Wall on gcc, no warnings on MSVC /W4 either.

https://godbolt.org/z/779Y4Ejzz

I'm sitting with the standard open but I must admit this is taking me forever to find. Do any of you know where to look?

EDIT: So far in my own research, I've got this from 21 years ago:

http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#232

At one point we agreed that dereferencing a null pointer was not undefined; only using the resulting value had undefined behavior.

🌐
Reddit
reddit.com › r/cpp_questions › what happens when dereferencing a nullptr?
r/cpp_questions on Reddit: What happens when dereferencing a nullptr?
August 18, 2022 -

I saw this code in A Tour of C++, but with a bit modify for illustration:

#include <iostream>

int main() {
  char s = 'a';
  char *p = &s;
  while (*p) {
    std::cout << *p;
    p++;
  }
  p = nullptr;
  //std::cout << (*p == true);
  *p == true;
}

I do not know how does while (*p) { end while I do not know what happens when p is nullptr. And std::cout << (*p == true) will induce segment fault but *p == true does not.

🌐
Reddit
reddit.com › r/c_programming › is it okay to dereference null array pointer?
r/C_Programming on Reddit: Is it okay to dereference null array pointer?
June 23, 2024 -

Quick question: Dereferencing pointer-to-array is basically a no-op, so is it legit even if the pointer is null?

int main(void)
{   int *ptr = 0 , printf(const char *, ...);
    printf("%p\n", (void *)*(int (*)[1])ptr);
    printf("wasn't actually dereferenced\n");
}

We first cast ptr to int (*)[1] and then dereference it (the void * cast is only meant for "%p").

The pedant in me says this is still undefined behavior, as the standard mentions:

If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.102)

102) ... Among the invalid values for dereferencing a pointer by the unary * operator are a null pointer, ...

Reference: https://port70.net/~nsz/c/c11/n1570.html#6.5.3.2p4

I'm looking for a second opinion, as I may have overlooked some part of the standard that implies my code is fine.

Motivation: Last month I posted a question to confirm if a well-known style of calling malloc works with VLA.

https://www.reddit.com/r/C_Programming/comments/1ck4azy/is_the_recommended_malloc_style_suitable_for_vla/

If the standard blesses dereference of invalid array pointer (due to no-op), then my earlier concern is also resolved.

🌐
Reddit
reddit.com › r/videos › you're dereferencing a null pointer!
r/videos on Reddit: You're dereferencing a null pointer!
July 1, 2017 - But you cant do a whole lot of stuff with 'the pointer'. ... Unmarshal errors, that's how! ... I do that so much in C# only to realize I had set a variable to a value by reference instead of by value in accident and the object went out of scope and became null ... Yeah all the time, just saying sometimes it's like someone created a null pointed and then immediately dereferenced it.
🌐
Reddit
reddit.com › r/ada › is it possible to avoid null pointer dereferencing in ada?
r/ada on Reddit: Is it possible to avoid null pointer dereferencing in Ada?
May 5, 2017 -

Hello, I learn how to code with Ada. I write the following code:

Test_Node_Ptr := Pull (Test_List);
Node_Deallocation (Test_Node_Ptr);
Put_Line ("Editted List:");
Print_List (Test_List);
Put_Line ("Pulled_Value:");
--   Put (Test_Node_Ptr.Value);

I think there is a null pointer dereferencing in the commented line. This is a link to the code line in repo.

It is strange that I found this error occasionally with valgrind, and before that commented code worked fine and printed the "right" value. So, why the memory wasn't cleaned and is it possible to avoid such situations in Ada? And is it possible to clean the memory for sure?

🌐
Reddit
reddit.com › r/embedded › what the hell gcc is doing (null ptr dereference)
r/embedded on Reddit: What the hell gcc is doing (NULL ptr dereference)
November 8, 2023 -

Guys, I'm programming cortex-m4 (stm32). I tried to read flash-memory(it is possible). Flash starts from 0. I tried to dereference NULL ptr and my mcu halted: printf("I'm dereferencing NULL pointer: %lx\r\n", *(uint32_t *)0);

Then I tried to dereference value 0x04 the same way, and it worked! I see the exact word from my binary firmware file. It means this memory region is accessible. I tried to figure out this weird thing and looked at assembly with this command: arm-none-eabi-objdump -d tanenbaum.out | less .

Look at this!: Instead of loading value to register, accessing memory region and passing it to printf and actually calling printf, like it did with number 0x04, compiler decides to insert unknown to me and cortex-m4 ISA instuction udf #255. (maybe there is such an instruction, but i didn't find it in programming manual).

8002108: 2300 movs r3, #0

800210a: 681b ldr r3, [r3, #0]

800210c: deff udf #255 ; unknown instruction

800210e: bf00 nop ; instead of branching to printf

What the hell? How do I avoid such an behavior of the compiler. How did the developers of gcc come up with this brilliant solution? So many questions... WHYYYY?? Maybe it indeed makes sense?

Btw, i assigned to variable value of 0 from user input (in runtime, so compiler makes no guesses about value), AND IT WORKED!. I've read the exact first word from binary firmware!

Find elsewhere
🌐
Reddit
reddit.com › r/programming › falsehoods programmers believe about null pointers
r/programming on Reddit: Falsehoods programmers believe about null pointers
September 15, 2025 - Dereferencing a null pointer is UB (#5 from the blog post must be assumed true), where anything may happen, so no assumptions can be made and must be avoided at all costs.
🌐
Reddit
reddit.com › r/golang › avoiding null ptr dereferences
r/golang on Reddit: Avoiding null ptr dereferences
April 17, 2023 -

EDIT: Conclusion if you find this thread in the future:

As of 2023-april-17, Go uses the old C approach to pointer safety: "Good programmers don't write bugs," although it is thankfully a defined (runtime) error rather than UB to read from a null pointer.

The compiler will not catch it if you write a function that reads from a pointer argument without checking for null.

Edit 2:

In response to this:

You seem unproportionately angry by this

I literally didn't believe my colleague when he complained about this earlier today, that's how incredible it is.

Null pointer dereferences have been a problem since the invention of null in 1965, a known problem since 1965+1, and remedies have been known and implemented in other languages for, at this point, literally decades.

  • C gets away with having this problem because it is too old.

  • Rust can do it because you have to specifically wrap code with unchecked dereferences in an "unsafe" region.

  • Zig has two kinds of pointers specifically to express these semantics.

  • C++ - terrible old C++ where everything is a catastrophe - recognizes this and lets you implement gsl::not_null<T>.

So I actually am kind of angry, yes. Having this problem in a modern compiled language is amateur hour. Having it in a language that isn't even used for Hard Realtime is professional malpractice by the inventors.

Original post:

A colleague has a null ptr dereference in Go.

I advised him to do as I would do - working in other languages, I tend to crank the warning level high and turn warnings into errors.

In e.g. C#, that means I cannot compile this code:

private static string bad_deref(object? Object)
{
    return Object.ToString();
}

because I get

  x.cs(y,z): [CS8602] Dereference of a possibly null reference.

Which, to be clear, is very good.

But he tells me Go doesn't have a warning level to crank and, googling, it would appear he is right.

So how do you solve this problem in Go? Are we back to good old C advice "good programmers don't make mistakes" and null ptr dereferences just sometimes happen if you don't work with perfect people?

🌐
Reddit
reddit.com › r/programming › dereferencing a null pointer always segfaults, right? not if you're clever...
r/programming on Reddit: Dereferencing a NULL pointer always segfaults, right? Not if you're clever...
March 31, 2010 - No one would do that. Dereferencing 0x00000000 can be made to work, but it has a different meaning from dereferencing NULL. ... No, that's not true. NULL is defined to be 0. The null pointer constant is always 0, which is the same as 0x0000000.
🌐
Reddit
reddit.com › r/cpp › null pointer dereferencing causes undefined behavior
r/cpp on Reddit: Null Pointer Dereferencing Causes Undefined Behavior
February 16, 2015 - Despite you being correct about ... it, regardless of platform characteristics. More replies ... You should never dereference nullptr under any circumstances!...
🌐
How Not To Code
hownot2code.wordpress.com › 2016 › 06 › 26 › never-dereference-null-pointers
Never dereference null pointers | How Not To Code
September 13, 2021 - The code contains an error that analyzer diagnoses in the following way: V595 The ‘tree’ pointer was utilized before it was verified against nullptr. Check lines: 134, 136. void mark_tree_uninteresting(struct tree *tree) { struct object *obj = &tree->object; if (!tree) return; .... } ... There is no doubt that it’s bad practice to dereference a null pointer, because the result of such dereferencing is undefined behavior.
🌐
Reddit
reddit.com › r/cpp_questions › why isn't a nullptr dereference an exception?
r/cpp_questions on Reddit: Why isn't a nullptr dereference an exception?
June 16, 2025 -

Just watched this video: https://www.youtube.com/watch?v=ROJ3PdDmirY which explains how Google manages to take down the internet (or at least: many sites) through a null pointer dereference.

Given that C++ has "nullptr" and that you can initialize stuff with it, and that you can (probably) statically check that variables / class members are initialized and balk if not, why isn't derefencing nullptr an exception? That would be the missing bit towards another bit of security in C++. So, why?

🌐
Reddit
reddit.com › r/rust › what happened when dereference a null pointer
r/rust on Reddit: what happened when dereference a null pointer
May 18, 2020 -

i tried out some code:

fn main() {

// Create a const NULL pointer

let nullp: *const u128 = ptr::null();

println!("size of null pointer:{}",mem::size_of_val(&nullp));

unsafe{

println!("null pointer is pointing to address {:p}", nullp);

println!("value the null pointer pointed is {}", *nullp);    

}

}

the output:

size of null pointer:8

null pointer is pointing to address 0x0

Segmentation fault (core dumped)

i wonder what happened when i try to deref a null pointer pointing to virtual memory address 0x0, at the low level?

and whats the actual memory layout of a null pointer?

Top answer
1 of 7
26
First, let's clear the easy: and whats the actual memory layout of a null pointer? The memory layout of a pointer, like for any value, depends only on its type, and does not depend on the current value stored inside it. That is, on a 64-bits machine, *mut T is 8 bytes (64 bits), regardless of whether it is null or not. i wonder what happened when i try to deref a null pointer at virtual memory address 0x0, at the low level? It depends upon the platform (combination of hardware, OS and run-time) that you are using. On a typical x64 computer, running Unix or Windows, the OS apportions virtual memory in pages of various sizes. On modern Linux, the typical sizes are 4 KB (normal), 2 MB (large), and 1 GB (huge). Since null-pointer dereferences are such a common issue, a common mitigation is to leave the first (few) pages of virtual memory unmapped. That is, the virtual memory page at address 0x0 is not mapped to a range of RAM. This uses the fact that when looking up memory, the CPU will need to map the virtual memory address to a real address in RAM to fetch the actual content. If no mapping exists, the CPU will raise a specific signal (Segmentation Fault) which will interrupt the program and, typically, will be handled by the OS. Here be dragons I did mention mitigation above. If, for example, you create a large slice with a null pointer and a large size, then the address 0x0 is not accessed itself, instead, when accessing slice[8192], the address 0x0 + 8192 is accessed. It may jump "past" the mitigation area, and not be detected. Also, the rules of the language mention that 0x0 is NOT a valid pointer to dereference, allowing the optimizer to assume it will never happen... which speeds up programs, at the cost of potentially unexpected behavior. I'll let Chris Lattner, from LLVM fame, explain the latter in detail: What every C programmer should know about Undefined Behavior 1/3 What every C programmer should know about Undefined Behavior 2/3 What every C programmer should know about Undefined Behavior 3/3
2 of 7
14
i wonder what happened when i try to deref a null pointer pointing to virtual memory address 0x0, at the low level? On a modern CPU it is roughly: CPU looks up the virtual address for 0x0 within the Translation Lookaside Buffer cache to translate this into a hardware address. This is because caches & fetches all function in hardware addresses, as far as the CPU is concerned. If the 0x0 address is not within the TLB (L1 or L2) it will look to the page table and preform a B+ Tree search for the address in question. This is so it can recover the hardware address, load the data in cache & registers like you expect. As a convention (meaning OS's will let you do this, but they recommend you don't) The 0-4095 address range isn't mapped. When you attempt to load an address which is not within the process's memory map the CPU raises an Interupt. The current executing process is halted, its registers are dumped to ram. Based on the Interrupt Descriptor Table the CPU will transfer control to "The Kernel", and report the interrupt. The Kernel will gently reassure The CPU that things are now under control. It looks up "your process" so it can send a signal "You accessed a non-mapped segment of memory, you're gonna lose your run permissions". If your process does not have a Segmentation Fault signal handler set up, the kernel destroys your process. All resources are freed, and your process is halted. In the rare event you do have a Segmentation Fault Signal handler setup, the kernel will execute this signal handler. It is up to "your code" to fix the situation. You'll notice I often refer to "The Kernel" and "The CPU". Meaning a programming language can't specify how any of this works, because the platform performs the whole process.
🌐
Secure Coding Blog
blog.bytehackr.in › understanding-and-preventing-null-pointer-dereference
Top 5 Way to Prevent NULL Pointer Dereference
May 8, 2025 - In this example, we declare an ... a null pointer dereference. When you run this code, it will likely result in a crash or an exception, such as a segmentation fault. The operating system detects the illegal memory access and terminates the program to prevent any further damage or instability. To avoid a null pointer ...
🌐
Quora
quora.com › How-do-I-avoid-dereferencing-null-pointers-in-C
How to avoid dereferencing null pointers in C - Quora
Answer (1 of 4): This is like asking “How do I avoid getting run over when I cross a street?” The answer? You check for cars before crossing. To avoid dereferencing a NULL pointer, check to make sure it’s not NULL before dereferencing it. That’s it. No fancy tricks.
🌐
Mayhem Security
mayhem.security › blog › what-is-null-pointer-dereference
What Is Null Pointer Dereference? | Mayhem
June 1, 2022 - Null pointer dereferences are particularly common in C and C++ programs, since these languages do not automatically check for NULL pointers. As a result, it is important for programmers to be careful when handling pointers in these languages. There are a few ways to avoid null pointer dereferences.
🌐
Medium
medium.com › @chanibonner › a-beginners-guide-to-null-pointer-dereference-attacks-d3618cc8a493
A Beginner’s Guide to Null Pointer Dereference Attacks | by Chani Bonner | Medium
February 25, 2024 - That’s what happens when a pointer has a null value. Let’s see what happens next. Now that you have an idea of what a NPD is, imagine for a minute someone tries to dereference a null pointer in the same way they would a pointer that contains a valid memory address.