Search code examples
cgcc-warning

-Wformat-truncation warning in gcc


The following is my code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
int main(int argc, char **argv){
    time_t curr_time;
    curr_time = time(NULL);
    struct tm tm = *localtime(&curr_time);
    char file_name[41];
    snprintf(file_name, sizeof(file_name), "backup_%02d.%02d.%02d-%02d.%02d.%02d.tar.lz4.gpg", tm.tm_mday, tm.tm_mon+1, tm.tm_year+1900, tm.tm_hour, tm.tm_min, tm.tm_sec); 
    printf("%s", file_name);
    return 0;
}

On running gcc -Wall -O3 ./gen.c, I get the following warning :

./gen.c: In function ‘main’:
./gen.c:11:77: warning: ‘%02d’ directive output may be truncated writing between 2 and 11 bytes into a region of size between 0 and 18 [-Wformat-truncation=]
   11 |     snprintf(file_name, sizeof(file_name), "backup_%02d.%02d.%02d-%02d.%02d.%02d.tar.lz4.gpg", tm.tm_mday, tm.tm_mon+1, tm.tm_year+1900, tm.tm_hour, tm.tm_min, tm.tm_sec);
      |                                                                             ^~~~
In file included from /usr/include/stdio.h:894,
                 from ./gen.c:1:
/usr/include/x86_64-linux-gnu/bits/stdio2.h:71:10: note: ‘__builtin___snprintf_chk’ output between 37 and 91 bytes into a destination of size 40
   71 |   return __builtin___snprintf_chk (__s, __n, __USE_FORTIFY_LEVEL - 1,
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   72 |                                    __glibc_objsize (__s), __fmt,
      |                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   73 |                                    __va_arg_pack ());
      |                                    ~~~~~~~~~~~~~~~~~

What does the warning mean and How do I solve this (I don't want to make the warning go away)?


Solution

  • The result of tm.tm_year+1900 will be at least four digits, not two. So %02d will not be enough, you need to use %04d.

    Also don't skimp on space for your array, there's really no need. With the two extra digits you're getting uncomfortably close to the size of the array.