在 C 中使用 sprintf 并收到警告时出现问题
Problem while using sprintf in C and getting warning
每当我在用 C 编写代码时尝试使用 sprintf() 时,我都会收到一条警告:
"warning: ‘%s’ directive writing up to 49 bytes into a region of size
39 [-Wformat-overflow=]"
它还生成一条注释说:
"note: ‘sprintf’ output between 13 and 62 bytes into a destination of
size 50 62 | sprintf(msg,"fopen-ing "%s"",data_file);"
下面我给出了我的部分代码,主要是我收到此警告的地方。
char data_file[50]; // Global
void initialize_from_data_file()
{
FILE *fpS;
if((fpS = fopen(data_file,"r")) == NULL)
{
char msg[50];
sprintf(msg,"fopen-ing \"%s\"",data_file);
perror(msg);
exit(1);
}
...
}
由于我刚开始使用这种语言,所以无法理解如何删除此警告。
警告您 sprintf
的目标缓冲区可能不够大,无法容纳您要放入其中的字符串。如果 data_file
的长度超过大约 40 个字符,sprintf
将写入数组 msg
.
的末尾
使 msg
足够大以容纳将放入其中的字符串:
char msg[70];
然而还有另一个问题。由于您在调用 perror
之前调用 sprintf
,后者将报告 sprintf
调用的错误状态,而不是 fopen
调用。
所以在这种情况下根本不要使用 sprintf
并使用 strerror
来获取错误字符串:
fprintf(stderr,"fopen-ing \"%s\": %s",data_file,strerror(errno));
每当我在用 C 编写代码时尝试使用 sprintf() 时,我都会收到一条警告:
"warning: ‘%s’ directive writing up to 49 bytes into a region of size 39 [-Wformat-overflow=]"
它还生成一条注释说:
"note: ‘sprintf’ output between 13 and 62 bytes into a destination of size 50 62 | sprintf(msg,"fopen-ing "%s"",data_file);"
下面我给出了我的部分代码,主要是我收到此警告的地方。
char data_file[50]; // Global
void initialize_from_data_file()
{
FILE *fpS;
if((fpS = fopen(data_file,"r")) == NULL)
{
char msg[50];
sprintf(msg,"fopen-ing \"%s\"",data_file);
perror(msg);
exit(1);
}
...
}
由于我刚开始使用这种语言,所以无法理解如何删除此警告。
警告您 sprintf
的目标缓冲区可能不够大,无法容纳您要放入其中的字符串。如果 data_file
的长度超过大约 40 个字符,sprintf
将写入数组 msg
.
使 msg
足够大以容纳将放入其中的字符串:
char msg[70];
然而还有另一个问题。由于您在调用 perror
之前调用 sprintf
,后者将报告 sprintf
调用的错误状态,而不是 fopen
调用。
所以在这种情况下根本不要使用 sprintf
并使用 strerror
来获取错误字符串:
fprintf(stderr,"fopen-ing \"%s\": %s",data_file,strerror(errno));