I am currently learning C and got stuck on this strange error. What strange is that this error doesn't occur on one compiler, but does occur on two others. Given that I am rather new to malloc, I figure that maybe I did something I shouldn't have.
Here is the code I am having trouble with:
#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;
}
I compile this file on a linux platform and got the following output:
Testing: 00000001
But on a C compiler on Windows and on codepad.org, I got the following output:
Testing: ����������00000001
I don't understand what is causing the extra characters before the cstring.