Why am I getting a warning in this C code using fprintf?

fprintf(pFile,msg.c_str()); 

why I get a warning in Xcode:

 Format string is not a string literal (potentially insecure) 

I assume that I am getting this warning to prevent attacks. msg contains some thing like %s that passes the stack to the screen until it completes zero completion. Is there a safe way to use fprintf in this case?

+4
source share
2 answers

You can specify a format string,

 fprintf(pFile, "%s", msg.c_str()); 

or use fputs ,

 fputs(msg.c_str(), pFile); 
+13
source

The reason your compiler warned you is because your way of printing a line could lead to a vulnerability called "line-string exploit" if the user could somehow affect the contents of the msg message on the extension, where he could add its own format specifiers ("% n", etc.). The suggested answer (fprintf (pFile, "% s", msg.c_str ());) fixes this because the format string is now constant.

You can read more about using formatted strings here: http://julianor.tripod.com/bc/formatstring-1.2.pdf

+10
source

All Articles