在 C 中使用 sprintf 时出现问题并收到警告

Dev*_*Dev 2 c printf

每当我在用 C 进行编码时尝试使用 sprintf() 时,我都会收到一条警告:

\n
\n

“警告:\xe2\x80\x98%s\xe2\x80\x99 指令将最多 49 个字节写入大小\n39 [-Wformat-overflow=] 的区域”

\n
\n

它还制作了一张纸条,上面写着:

\n
\n

"注意:\xe2\x80\x98sprintf\xe2\x80\x99 将 13 到 62 字节输出到大小为 50 62 的目标中 | sprintf(msg,"fopen-ing "%s"",data_file);"

\n
\n

下面我给出了我的代码的一部分,主要是我收到此警告的地方。

\n
char data_file[50]; // Global\n\nvoid initialize_from_data_file()\n{\n    FILE *fpS;\n    if((fpS = fopen(data_file,"r")) == NULL)\n    {\n        char msg[50];\n        sprintf(msg,"fopen-ing \\"%s\\"",data_file);\n        perror(msg);\n        exit(1);\n    }\n    ...\n}\n
Run Code Online (Sandbox Code Playgroud)\n

由于我最近使用这种语言,所以无法理解如何删除此警告。

\n

dbu*_*ush 8

它警告您目标缓冲区sprintf可能不够大,无法容纳您要放入其中的字符串。如果data_file长度超过 40 个字符左右,sprintf则会写入数组末尾msg

使其msg足够大以容纳要放入其中的绳子:

char msg[70];
Run Code Online (Sandbox Code Playgroud)

然而还有另一个问题。由于您sprintf在调用之前调用perror,因此后者将报告调用的错误状态sprintf,而不是fopen调用的错误状态。

sprintf因此,在这种情况下根本不要使用并使用strerror来获取错误字符串:

fprintf(stderr,"fopen-ing \"%s\": %s",data_file,strerror(errno));
Run Code Online (Sandbox Code Playgroud)