我目前在学习C并陷入了这个奇怪的错误。奇怪的是,这个错误不会发生在一个编译器上,而是在另外两个编译器上发生。鉴于我对malloc相当陌生,我认为我可能做了一些我不应该拥有的东西。Malloc printf开头的奇怪字符
这里是我遇到的麻烦的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* int_to_binary(unsigned int x)
{
char *str = (char *) malloc(sizeof(char)*9);
int z;
for (z = 128; z > 0; z >>= 1)
{
strcat(str, ((x & z) == z) ? "1" : "0");
}
return str;
}
int main()
{
printf("Testing: %s\n", int_to_binary(1));
return 0;
}
我编译在Linux平台上这个文件,并得到了以下的输出:
测试:00000001
但在C编译器在Windows和codepad.org上,我得到了以下输出:
测试: 00000001
我不明白是什么造成了cstring之前的额外字符。
[不使用C强制转换malloc(http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar