1. 23
    1. 4

      It also happens on OpenBSD.

      1. 4

        What happens on OpenBSD?

        $ vi null.c
        $ make null
        cc -O2 -pipe    -o null null.c 
        $ ./null                                                                                                                                      
        Segmentation fault (core dumped) 
        $ sysctl kern.version                                                                                                                         
        kern.version=OpenBSD 5.8 (GENERIC) #1153: Mon Aug  3 05:31:43 MDT 2015
            deraadt@amd64.openbsd.org:/usr/src/sys/arch/amd64/compile/GENERIC
        
        $ cat null.c                                                                                                                                  
        null.c     null.core  
        $ cat null.c 
        #include <stdio.h>
        
        int
        main(int argc, char * argv[])
        {
        
                printf("%s\n", NULL);
        }
        
        $
        

        From gdb on the core file:

        Core was generated by `null'.
        Program terminated with signal 11, Segmentation fault.
        
        #0  strlen () at /usr/src/lib/libc/arch/amd64/string/strlen.S:124
        124     /usr/src/lib/libc/arch/amd64/string/strlen.S: No such file or directory.
                in /usr/src/lib/libc/arch/amd64/string/strlen.S
        (gdb) bt
        #0  strlen () at /usr/src/lib/libc/arch/amd64/string/strlen.S:124
        #1  0x00001e30183ddade in puts (s=0x0) at /usr/src/lib/libc/stdio/puts.c:45
        #2  0x00001e2d521009f1 in _start () from /home/mulander/code/c/null
        #3  0x0000000000000000 in ?? ()
        Current language:  auto; currently asm
        (gdb) Quit
        
        1. 13

          That’s because gcc helpfully replaces printf with fputs. Try a format string like “null prints like %s\n”.

          1. 3

            Hah! Thanks learned something interesting today :)

            printf("test: %s\n", NULL);
            
            
            $ ./null                                                                                                                                      
            test: (null)
            
            1. 3

              Wait, what? wtf?

              If I asked for printf, I want printf.

              1. 10

                I mean it’s an optimizing compiler, and it knows lots of things that can be optimized.