Break things, write reports

Damnit C / Format Strings

Compiler defaults should be sensible

Tags — | Categories: — dev |
Posted at — Jan 21, 2022

Consider the following:

$ cat cock.c 
#include <stdio.h>
int main() {

    printf("%dcock");
}

Compile it, run it:

$ gcc cock.c && ./a.out

-1463120536

The output here probably isn’t what one intended, but it’s what you get. Of course, -Wall will warn you about this, and you might notice it, then fix it:

$ gcc -Wall cock.c 
cock.c: In function ‘main’:
cock.c:4:18: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=]
    4 |         printf("%dcock");
      |                 ~^
      |                  |
      |                  int

As opposed to languages such as Rust, where this immediately gets flagged without any special config and won’t let you continue:

$ cat rust.rs 
fn main() {

    println!("fuuu{}");
}

$ rustc rust.rs 
error: 1 positional argument in format string, but no arguments were given
 --> rust.rs:3:19
  |
3 |     println!("fuuu{}");
  |                   ^^

error: aborting due to previous error

The above is a pretty good, simple example of shipping tools with sensible defaults.

Sidenote: Although slightly constrained - the C compiler does have sensible defaults; they’re just not going to produce what we intended to write.