null pointer dereference detection in DMD

Walter Bright newshound2 at digitalmars.com
Sat Jan 11 01:43:07 UTC 2025


Consider:
```
void main()
{
     int* p;
     *p = 3;
}
```
Compiling it and running it results in "Segmentation fault (core dumped)".

But compiling it with -O results in a compile time error:

```
Error: null dereference in function _Dmain
```

What's happening here? The optimizer does DFA (Data Flow Analysis) and can 
statically determine that `p` is null when deferenced.

(The message is a bit generic because the optimizer turns the source code into 
hamburger, and the cow is not easily reconstructed.)

Curiously, compiling it with `gcc -O3` does not detect it. ImportC doesn't 
detect it, either, a choice made because some C code uses such a construct as a 
way to drop into the debugger.


More information about the Digitalmars-d mailing list