在c上打印char的意外行为
我得到当我尝试在文件中打印字符串时,这些意外的chars。我该如何处理这种情况?
这是我的代码:
#include <stdlib.h>
#include <stdio.h>
char *readFile(char *filename)
{
char * buffer;
long length;
FILE * f = fopen (filename, "r");
if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = malloc (length);
if (buffer)
{
fread (buffer, 1, length, f);
}
fclose (f);
}
return buffer;
}
int main() {
char *firstS = readFile("file.txt");
printf("%s \n", firstS);
return 0;
}
I am getting these unexpected chars when I try to print the string inside of a file. How can I deal with this situation?
This is my code:
#include <stdlib.h>
#include <stdio.h>
char *readFile(char *filename)
{
char * buffer;
long length;
FILE * f = fopen (filename, "r");
if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = malloc (length);
if (buffer)
{
fread (buffer, 1, length, f);
}
fclose (f);
}
return buffer;
}
int main() {
char *firstS = readFile("file.txt");
printf("%s \n", firstS);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不是
nul
终止字符串。取而代之的是,请执行此操作,然后在文件中读取 时
当
printf
读取buffer
时, ,它会调用不确定的行为,printf
愉快地读取,直到找到一个'\ 0''
。另请注意,您应该初始化buffer
为null:并在打印之前在
main
中检查。如果打开文件有问题,则您将一个非初始化的buffer
返回到main
,然后尝试从中读取这是另一个UB调查器:You're not
NUL
terminating your string. Instead, doand then after you read in the file
When
printf
reads past the allocated memory forbuffer
, it invokes undefined behavior,printf
happily reads along until it finds a'\0'
. Also note you should initializebuffer
to NULL:and check for that back in
main
before you print. If there's a problem opening the file for instance, you return an uninitializedbuffer
tomain
, and trying to read from that is another UB invoker: