Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

c - fprintf, error: format not a string literal and no format arguments [-Werror=format-security

when I try to compile fprintf(stderr,Usage) on Ubuntu I got this error:

 error: format not a string literal and no format arguments [-Werror=format-security

but when I compiled that on other linux distributions (RedHat, Fedora, SUSE) that is compiled successfully.

Anyone has an idea?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use fputs(Usage, stderr);

There is no need to use fprintf if you arn't doing formatting. If you want to use fprintf, use fprintf(stderr, "%s", Usage);

The default compiler flags on Ubuntu includes -Wformat -Wformat-security which is what gives this error.

That flag is used as a precaution against introducing security related bugs, imagine what would happen if you somehow did this:

char *Usage = "Usage %s, [options] ... ";
...
fprintf(stderr, Usage);

This would be the same as fprintf(stderr, "Usage %s, [options] ... ]"); which is wrong.

Now the Usage string includes a format specifier, %s, but you do not provide that argument to fprintf, resulting in undefined behavior, possibly crashing your program or allowing it to be exploited. This is more relevant if the string you pass to fprintf comes from user input.

But if you do fprintf(stderr,"%s", "Usage %s, [options] ... ]"); There is no such problem. The 2. %s will not be interpreted as a format specifer. gcc can warn about this, and the default Ubuntu compiler flags makes it a compiler error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...