Menu

#180 -Wformat-truncation likely pointing out an actual bug

v1.0_(example)
closed
nobody
None
1
2026-02-19
2025-04-07
No

The Makefile on branch master has an explicit -Wno-format-truncation (starting with no-) but when re-enabling that warning via -Werror=format-truncation we can see that writing " %02x" with size 3 will always write (1) a space, (2) one hex digit and (3) a null byte (but not the second hex digit). For proof:

$ cat main.c 
#include <stdio.h>

int main(void) {
    char buffer[] = "123456789";
    int res = snprintf(buffer + 3, 3, "XXX");
    printf("res = %d, buffer = \"%s\"\n", res, buffer);
    return 0;
}

$ gcc main.c && ./a.out 
res = 3, buffer = "123XX"

If that's the intention, dividing by 16 (and then potentially module 16 to ensure 0<=x<=15?) and using " %x" for a format should fix the warning and make the intentions clear. If it is a bug, then the fix is even simpler. What do you think?

The compiler output from Clang 19 is this:

giftext.c:441:10: warning: 'snprintf' will always be truncated; specified size is 3, but format string expands to at least 4 [-Wformat-truncation]
  441 |                         (void)snprintf(&HexForm[CrntPlace * 3], 3, " %02x",
      |                               ^
giftext.c:487:9: warning: 'snprintf' will always be truncated; specified size is 3, but format string expands to at least 4 [-Wformat-truncation]
  487 |                 (void)snprintf(&HexForm[CrntPlace * 3], 3, " %02x",
      |                       ^

Thanks for your consideration!

Best, Sebastian

CC @ctulhu

Discussion

  • Eric S. Raymond

    Eric S. Raymond - 2026-02-19
    • status: open --> closed
     
  • Eric S. Raymond

    Eric S. Raymond - 2026-02-19

    Fix pushed.

     

Log in to post a comment.

MongoDB Logo MongoDB