0

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.

Ice Drake
  • 89
  • 1
  • 13
  • 2
    [don't cast malloc in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Oct 26 '15 at 23:50

1 Answers1

2

You can't strcat() to an uninitialized buffer, it expects its first parameter to be nul terminated. Also using strcat() like that is a bad idea, you should use pointer artihmetics to append the character and nul terminate str in order to pass it to printf().

char *ptr;

ptr = str;
for (z = 128 ; z > 0 ; z >>= 1, ptr++)
    *ptr = ((x & z) == z) ? '1' : '0';
*ptr = '\0';
R Sahu
  • 204,454
  • 14
  • 159
  • 270
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • Ah, that was what the problem. It concatenates after the buffer I initialized via malloc till a null terminator. Thanks. – Ice Drake Oct 27 '15 at 00:04