C程序打印字符怪异

C程序打印字符怪异

本文介绍了C程序打印字符怪异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,读取一个文件的内容,并将其保存到 BUF 。读取内容之后它应该两个两个字符复制到阵列。这code工作正常,如果我不是从文件中读取,但如果我尝试从文件中读取它从缓冲区中的printf打印,我想这两个字符,但增加了奇怪的字符。我已经证实,它的正确保存到buf中,没有奇怪的字符出现。我无法弄清楚什么是错的......这里的code:

 的char *缓冲区=(字符*)malloc的(2 * sizeof的(炭));
字符* DST =缓冲;
字符* SRC = BUF;
字符*结束= BUF +的strlen(BUF);
字符*宝宝='\\ 0';
而(SRC< =结束)
{
    函数strncpy(DST,SRC,2);
    SRC + = 2;
    的printf(%S \\ n,缓冲区);
}


解决方案

  1. (字符*)malloc的(2 * sizeof的(炭)); 更改为的malloc(3 * sizeof的*缓冲区); 你需要一个额外的字节来存储用来指示终止空字符结束的字符串。 ASLO,不投的malloc的返回值()


  2. 在你的情况下,函数strncpy(),您提供的 N 2 ,这是没有任何范围,存储终止空字节。没有trminating空,的printf()将不知道在哪里停下来。现在,3个字节的内存,你可以使用的strcpy()来正确复制字符串


函数strncpy()不可以添加终止空本身,以防 N 等于提供的缓冲区的大小,从而成为非常非常不可靠的(不像的strcpy())。你需要照顾它编程。

检查这里。

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 = '\0';
while (src<= end)
{
    strncpy(dst, src, 2);
    src+= 2;
    printf("%s\n", buffer);
}
解决方案
  1. (char*)malloc(2*sizeof(char)); change to malloc(3*sizeof*buffer); You need an additional byte to store the terminating null character which is used to indicate the end-of-string. Aslo, do not cast the return value of malloc().

  2. 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() 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.

check the man page for strncpy() and strcpy() here.

这篇关于C程序打印字符怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 00:24
查看更多