Home > Net >  Can't resolve snprintf warning in C
Can't resolve snprintf warning in C

Time:03-03

Facing a warning which I am not able to resolve. I am using stm32 MCU and STM32CubeIDE with a standard C11 compiler. I can easily get rid of the warning by increasing size of the array gStr but would like to know what is the issue here. Current size of gStr looks adequate to hold the given data. Any help is appreciated. Thank you!

The global definitions of the variables used looks like this:

#define LOG_ERROR_FILENAME_MAX_LEN  30
#define LOG_ERROR_MAX_ENTRY 30
#define LOG_GSTR_SIZE   128     //changed from 128 to 2048 to remove warning

typedef struct
{
    char fileName[LOG_ERROR_FILENAME_MAX_LEN];
    u16 line;
    u16 hits;
} LogEntryType;

static LogEntryType gLogEntrys[LOG_ERROR_MAX_ENTRY];
u8 gLogEntryCount = 0;
static char gStr[LOG_GSTR_SIZE];

The function call where the warning is generated looks like this:

snprintf(gStr, LOG_GSTR_SIZE, "%s line:%u hits:%u",gLogEntrys[i].fileName, gLogEntrys[i].line, gLogEntrys[i].hits);

The snprintf call is generating the following warning

../User/Utils/log_error.c: In function 'cliCmdDisplayLog':
../User/Utils/log_error.c:54:36: **warning**: '%s' directive output may be truncated writing up to 1019 bytes into a region of size 128 [-Wformat-truncation=]
   54 |     snprintf(gStr, LOG_GSTR_SIZE, "%s line:%u hits:%u",
      |                                    ^~
../User/Utils/log_error.c:54:35: note: directive argument in the range [0, 65535]
   54 |     snprintf(gStr, LOG_GSTR_SIZE, "%s line:%u hits:%u",
      |                                   ^~~~~~~~~~~~~~~~~~~~
../User/Utils/log_error.c:54:35: note: directive argument in the range [1, 65535]
../User/Utils/log_error.c:54:5: note: 'snprintf' output between 15 and 1042 bytes into a destination of size 128
   54 |     snprintf(gStr, LOG_GSTR_SIZE, "%s line:%u hits:%u",
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   55 |      gLogEntrys[i].fileName, gLogEntrys[i].line, gLogEntrys[i].hits);
      |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

CodePudding user response:

Judging from the symptoms, I think your problem is a variant of the problem reported to GCC as GCC Bug 95755, reported in June 2020 but not yet fixed.

There is an outline workaround in the response to the report. You would need to use limits in the format strings (%*.*s or %.*s with integers specifying the length), or you'd need to create the format string on the fly with one snprintf() operation creating the format string and a second using it.

  • Related