0

I'be build this function to convert integers to binary strings

char* numberToBinary(int num){
    char arr[11];
    int x=1;
    for(int i=0;i<10;i++){
        arr[9 - i] = (num & x)?'1':'0';
        x = x<<1;
    }
    arr[10] = '\0';
    char* res = &arr[0];
    printf("%s\n", res);//prints 0000000100
    return res;
}
printf("%s\n", numberToBinary(4));//prints changeable binary data

The problem is inside the function the variable res has the correct answer, but it looks like the retrieved value from the function I guess is the location of the variable res, which has been de-located from memory.

How can I make the function numberToBinary return a string inside of something else.

Abozanona
  • 2,261
  • 1
  • 24
  • 60
  • 4
    You're returning the address of a local variable. This is a grave mistake which your compiler should've warned you about. – Daniel Kamil Kozar Aug 16 '17 at 20:51
  • `char arr[11];` --> `static char arr[11];` – BLUEPIXY Aug 16 '17 at 20:54
  • Also, UB aside, you can just change that to `printf("%s\n", arr);`. In this case, `arr` will decay to a pointer to its first element (`char*`) and that will `printf` just fine .. no need for `res` – yano Aug 16 '17 at 20:59
  • @T.J.Crowder This is the usage assumed by OP. (Make a copy if necessary) note that `printf("%s\n", numberToBinary(4));` will cause a memory leak if memory is secured using `malloc`. – BLUEPIXY Aug 16 '17 at 21:03
  • @BLUEPIXY: I don't see that the OP said they wanted to reuse the same buffer for two completely unrelated calls, and create the crosstalk that would invite in their app. – T.J. Crowder Aug 16 '17 at 21:04
  • @T.J.Crowder It is the same as reuse you say. In my case it is speculation from the code. – BLUEPIXY Aug 16 '17 at 21:08
  • Change `char arr[11];` to `static char arr[11];`and `printf("%s\n", res);' to `printf("%s\n", arr);` finally return `arr` – MCG Aug 16 '17 at 21:12

1 Answers1

1

Returning address of local variable leads to undefined behavior, becouse it is not in scope (ended its lifetime) in the time you are passing it to printf().

You have to pass an array to function as parameter, or allocate char* res on heap (dynamic storage duration).

Example

char* res = malloc (amountOfBytesYouNeed);
if (res == NULL) { /*err msg*/ exit(-1); }
// Store data to res insted of arr
return res;

//
char * ptr = numberToBinary(4);
printf("%s\n", ptr);
free(ptr); // !
kocica
  • 6,412
  • 2
  • 14
  • 35