PSA: You cannot use %.*s to print strings with NUL bytes

2 points by gray_-_wolf ↗ HN
Following does not do what most people would expect:

    +$ cat main.c
    #include <stdio.h>
    
    int main(void) {
     char str[] = { 0, 'a' };
     printf("`%.*s'\n", sizeof(str), str);
     return 0;
    }
    +$ gcc -o main main.c
    +$ ./main 
    `' 
This post was triggered by seeing comment suggesting just this (and I can't reply since it is too old). But people should be warned.

1 comment

[ 1.3 ms ] story [ 14.4 ms ] thread
You shouldn't be too surprised: C strings are null terminated.