dmd's optimizer detects intraprocedural cases of null dereferences

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Sat Jul 27 19:12:02 UTC 2024


It would help if you turned on the analysis ;)

```c
int main(int argc, char** argv)
{
      int* p = (int*)0;
      *p = 3;
      return 0;
}
```

GCC args: ``-fanalyzer``

GCC Output:

```
<source>: In function 'main':
<source>:4:9: warning: dereference of NULL 'p' [CWE-476] 
[-Wanalyzer-null-dereference]
     4 |      *p = 3;
       |      ~~~^~~
   'main': events 1-2
     |
     |    3 |      int* p = (int*)0;
     |      |           ^
     |      |           |
     |      |           (1) 'p' is NULL
     |    4 |      *p = 3;
     |      |      ~~~~~~
     |      |         |
     |      |         (2) dereference of NULL 'p'
     |
ASM generation compiler returned: 0
<source>: In function 'main':
<source>:4:9: warning: dereference of NULL 'p' [CWE-476] 
[-Wanalyzer-null-dereference]
     4 |      *p = 3;
       |      ~~~^~~
   'main': events 1-2
     |
     |    3 |      int* p = (int*)0;
     |      |           ^
     |      |           |
     |      |           (1) 'p' is NULL
     |    4 |      *p = 3;
     |      |      ~~~~~~
     |      |         |
     |      |         (2) dereference of NULL 'p'
     |
Execution build compiler returned: 0
Program returned: 139
Program terminated with signal: SIGSEGV
```

CLANG args: ``--analyze``

CLANG Output:

```
clang: warning: -Wl,-rpath,./lib: 'linker' input unused 
[-Wunused-command-line-argument]
clang: warning: -Wl,-rpath,/opt/compiler-explorer/gcc-13.2.0/lib64: 
'linker' input unused [-Wunused-command-line-argument]
clang: warning: -Wl,-rpath,/opt/compiler-explorer/gcc-13.2.0/lib32: 
'linker' input unused [-Wunused-command-line-argument]
clang: warning: argument unused during compilation: '-L./lib' 
[-Wunused-command-line-argument]
<source>:4:9: warning: Dereference of null pointer (loaded from variable 
'p') [core.NullDereference]
     4 |      *p = 3;
       |       ~ ^
1 warning generated.
ASM generation compiler returned: 0
clang: warning: -Wl,-rpath,./lib: 'linker' input unused 
[-Wunused-command-line-argument]
clang: warning: -Wl,-rpath,/opt/compiler-explorer/gcc-13.2.0/lib64: 
'linker' input unused [-Wunused-command-line-argument]
clang: warning: -Wl,-rpath,/opt/compiler-explorer/gcc-13.2.0/lib32: 
'linker' input unused [-Wunused-command-line-argument]
clang: warning: argument unused during compilation: '-L./lib' 
[-Wunused-command-line-argument]
<source>:4:9: warning: Dereference of null pointer (loaded from variable 
'p') [core.NullDereference]
     4 |      *p = 3;
       |       ~ ^
1 warning generated.
Execution build compiler returned: 0
Program returned: 255
[F][2024-07-27T19:10:38+0000][1] runChild():487 Launching child process 
failed
```


More information about the Digitalmars-d mailing list