C程序打印奇怪的字符 [英] C program printing weird characters
问题描述
我有一个程序可以读取文件的内容并将其保存到 buf
中.阅读内容后,它应该将两个两个字符复制到一个数组中.如果我不尝试从文件中读取,则此代码可以正常工作,但是如果我尝试从文件中读取它,则缓冲区中的 printf 会打印我想要的两个字符,但会添加奇怪的字符.我已经确认并且它正确保存到 buf 中,那里没有奇怪的字符.我不知道出了什么问题...这是代码:
I have a program that reads the content of a file and saves it into buf
. After reading the content it is supposed to copy two by two chars to an array. This code works fine if I'm not trying to read from a file but if I try to read it from a file the printf from buffer prints the two chars that I want but adds weird characters. I've confirmed and it's saving correctly into buf, no weird characters there. I can't figure out what's wrong... Here's the code:
char *buffer = (char*)malloc(2*sizeof(char));
char *dst = buffer;
char *src = buf;
char *end = buf + strlen(buf);
char *baby = ' ';
while (src<= end)
{
strncpy(dst, src, 2);
src+= 2;
printf("%s
", buffer);
}
推荐答案
(char*)malloc(2*sizeof(char));
改为malloc(3*sizeof*buffer);
你需要一个额外的字节存储用于指示end-of-string
的终止空字符.另外,不要强制转换malloc()
的返回值.感谢放松
(char*)malloc(2*sizeof(char));
change tomalloc(3*sizeof*buffer);
You need an additional byte to store the terminating null character which is used to indicate theend-of-string
. Aslo, do not cast the return value ofmalloc()
. Thanks to unwind
在您的情况下,使用 strncpy()
,您提供了 n
作为 2
,它没有任何范围存储终止的空字节.如果没有终止 null,printf()
将不知道在哪里停止.现在,有了 3 个字节的内存,您可以使用 strcpy()
正确复制字符串
In your case, with strncpy()
, you have supplied n
as 2
, which is not having any scope to store the terminating null byte. without the trminating null, printf()
won't be knowing where to stop. Now, with 3 bytes of memory, you can use strcpy()
to copy the string properly
strncpy()
将不添加终止 null 本身,以防 n
等于提供的缓冲区的大小,从而成为非常非常不可靠(不像 strcpy()
).您需要以编程方式处理它.
strncpy()
will not add the terminating null itself, in case the n
is equal to the size of supplied buffer, thus becoming very very unreliable (unlike strcpy()
). You need to take care of it programmatically.
查看 strncpy()
和 strcpy 的手册页()
在这里.
check the man page for strncpy()
and strcpy()
here.
这篇关于C程序打印奇怪的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!