Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么在C代码中使用fprintf会得到警告?_C++_C_Xcode_String Formatting - Fatal编程技术网

C++ 为什么在C代码中使用fprintf会得到警告?

C++ 为什么在C代码中使用fprintf会得到警告?,c++,c,xcode,string-formatting,C++,C,Xcode,String Formatting,为什么我会在Xcode中收到警告: fprintf(pFile,msg.c_str()); 我假设我得到这个警告是为了防止攻击,因为msg包含了一些类似%s的东西,它将堆栈流到屏幕上,直到到达null终止。在这种情况下,是否有安全的方法使用fprintf?您可以给出一个格式字符串 Format string is not a string literal (potentially insecure) 或使用fputs fprintf(pFile, "%s", msg.c_str()); 编

为什么我会在Xcode中收到警告:

fprintf(pFile,msg.c_str());

我假设我得到这个警告是为了防止攻击,因为msg包含了一些类似
%s
的东西,它将堆栈流到屏幕上,直到到达null终止。在这种情况下,是否有安全的方法使用fprintf?

您可以给出一个格式字符串

Format string is not a string literal (potentially insecure)
或使用
fputs

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

编译器警告您的原因是,如果用户能够以某种方式影响msg的内容,并在一定程度上使用自己的格式说明符(“%n”,等等),那么您打印字符串的方式可能会导致名为“格式字符串攻击”的漏洞。建议的答案(fprintf(pFile,“%s”,msg.c_str());)解决了这个问题,因为格式字符串现在是常量


您可以在此处阅读有关格式化字符串漏洞的更多信息:

fprintf(pFile,“%s”,msg.c_str())是否有。@DanielFischer添加为答案?
fputs(msg.c_str(), pFile);