How to fix warning 'sprintf' swriting a termination nul past the end ot the destination [-Wformat-overflow=]

Viewed 45

Below is my code and when I compile this, warning comes up ..

Please let me know how to fix it

sprintf(gsErrLog.aPrgmNm, "%-15.15s", pzArgv[0]);
                          ^
char gsErrLog.aPrgmNm [15];

warning: 'sprintf' writing a termination nul past the end of the destination [-Wformat-overflow=]

1 Answers
char gsErrLog.aPrgmNm [15];
sprintf(gsErrLog.aPrgmNm, "%-15.15s", pzArgv[0]);

Do this:

char gsErrLog.aPrgmNm [16];
snprintf(gsErrLog.aPrgmNm, sizeof(gsErrLog.aPrgmNm), "%-15.15s", pzArgv[0]);
  • A 15 length sprintf() doesn’t have enough space to store in a 15 character array of char. You will need room for the null (\0) at the end.
  • Always use snprintf(), as it permits a limitation on how many characters to write.
Related