-1

I am trying to compile my code with gcc 8.

i am facing following warnings :-

warning:  [-Wformat-truncation=]
120 |         snprintf( test, sizeof test, "%s", testpath);

With gcc 5 i am able to compile. But with gcc 8 i am facing this issue.Could you please help what needs to be done here to fix this issue in-order to compile this on GCC 8.

Naga
  • 59
  • 8
  • 2
    It's a warning, so the compilation still succeeds, unless you compile with `-Werror`. Also read this: https://stackoverflow.com/questions/51534284/how-to-circumvent-format-truncation-warning-in-gcc – Jabberwocky Aug 03 '20 at 06:52
  • Yeah, But how can we fix this in my code? – Naga Aug 03 '20 at 06:55

1 Answers1

7

You are expected to be using e.g. %.254s or in your case %.221s/%.32s explicitly to specify that you are only going to process the first 254 characters of the parameter in any case.

That warning is supposed to ensure that you don't end up with an unexpectedly truncated string on the output side, but rather truncate the input in a meaningful way.

Alternatively, you should check the return value of snprintf. If negative, then the output was truncated.

GCC9 will warn you when you did neither truncate the input (guaranteeing that no output truncation could have occurred), nor performed error handling in case the output got truncated.


In your specific case, it looks as if you are constructing a path (which is useless when truncated in any form), so validating the return value of snprintfis what you actually should do.

Ext3h
  • 5,713
  • 17
  • 43