Yazan W Yusuf Yazan W Yusuf - 1 year ago 55
C Question

value of string changes after function ends

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.

Answer Source

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); // !
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download