Search code examples
cgcc-warninggcc11

warning: '__builtin_snprintf' output may be truncated before the last format character [-Wformat-truncation=]


warning: ‘__builtin_snprintf’ output may be truncated before the last format character [-Wformat-truncation=]
  "%s", evspan->text);
     ^

len = strlen(evspan->text);
evspan->ent->content = malloc(len+1);

snprintf(evspan->ent->content, len,
"%s", evspan->text);

I saw this warning on gcc 8. How do I prevent this without using -Wformat-truncation option?


Solution

  • The second argument to snprintf is the length of the buffer, not the maximum string length.

    The call should be:

    snprintf(evspan->ent->content, len + 1, "%s", evspan->text);
    

    This matches the length passed to malloc.


    The comments given on snprintf not being the best choice do apply, if your full code is as simple as what's shown here.