字符串末尾打印的奇怪符号 - C

Weird Symbols printed at end of string - C

所以,我有一个程序可以解析一行文本中的表达式,例如

11110000 & 11001100 ;

并评估二进制结果。我的代码正确解析并正确评估,但是对于我的两个测试输入(包括上面的那个),我的 printf 也在每个 运行.

之后打印这些奇怪的符号
eos$ ./interpreter < program02.txt
11000000 +
eos$ ./interpreter < program02.txt
11000000 2ñ
eos$ ./interpreter < program02.txt
11000000 "]
eos$ ./interpreter < program02.txt
11000000 ÒØ
eos$ ./interpreter < program02.txt
11000000 Ê
eos$ ./interpreter < program02.txt
11000000 òJ

字符串是这样 malloc 的

char *str = ( char * ) malloc ( ( getLength( src ) + 1 ) * sizeof( char ) );

下面是字符串的打印方式

char *str = binaryToString( val );
printf( "%s\n", str );

任何帮助都会很棒!谢谢!

字符串在 C 语言中以 null 结尾。当您 malloc() 内存时,它将被之前块中的任何内容填充。

一种解决方案是在使用 malloc() 之后通过 memset()(在 string.h 中找到)用空字符 [=13=] 填充缓冲区:

int strLen = getLength(src) + 1;
char *str = (char*)malloc(strLen * sizeof(char));
memset(str, '[=10=]', strLen); // Fill with null chars

同样你可以在最后一个字符后写一个[=13=]

编辑: 根据 iharob 的评论,这不是好的建议。考虑到这一点,并假设您知道字符串的长度:

int strLen = getLength(src) + 1;
char *str = calloc(strLen, sizeof(char)); // Allocate strLen * sizeof(char)
if (str == NULL) {
    // Error allocating str - handle error
}
str[strLen - 1] = '[=11=]'; // zero-based, so char is after final character

是更好的解决方案。