Value of string magically changes after function is used on a different string

70 Views Asked by At

enter image description here

As shown in this dbg debug log, string1 = '0' <repeats 28 times>, "1000" is printed after the intToBinary(num1, string1) function call. But then on the next instruction intToBinary(num2, string2) is called. As you can see different parameters are passed to the intToBinary function. How come the variable string1 is affected by the second time the function is called using different variables? In the log it says the first character changes from 0 to \ (or \0?).

Here's the pastebin of the function in case necessary. http://pastebin.com/EsQNMjej

void intToBinary(int num, char* string)
{
    string[32] = '\0';
    int i,j;
    int temp = num;

    // is num negative?
    int isNegative = num < 0 ? 1 : 0;

    //negate all bits and add 1 (two complements)
    if(isNegative)
    {
        temp = -1 * temp; //absolute value

        //In order to get the negative number in
        // 2's complement you can either negate and
        // increment, or decrement by 1 and negate.
        //In this function, temp gets negated after
        //the conversion to string
        --temp;
    }

    //Write binary of positive num to string
    for(i = 0, j = 31; i < 32; i++,j--)
    {
        if(pow(2,j) <= temp)
        {
           //Temp is decreased when the bit is 1
           temp = temp - pow(2, j);
           string[i] = '1';
        }
        else
        {
            //Nothing happens to temp when the bit is 0
            string[i] = '0';
        }
    }

    if(isNegative)
    {
        for(i = 0; i < 32; i++)
        {
            //negate bits
            string[i] = string[i] == '1' ? '0' : '1';
        }
    }
}

I just don't get what's going on here. I tried switching the order of the two function calls, so it got changed to the following

intToBinary(num2, string2);
intToBinary(num1, string1);

And magically, the first byte stays '0', which is what I want. But now I just want to know why this changed in the first place...

2

There are 2 best solutions below

2
On BEST ANSWER

string[32] = '\0';

That overflows your input buffer. And I think you'll find that your string1 is immediately after string2 in memory. So overflowing string2 by 1 byte will run into string1.

0
On

You're trying to store a 32-bit binary number in 32 bytes; you forgot to allocate an extra byte for the null terminator. When the null is written after string2, it clobbers the start of string1.

Undefined behaviour (writing beyond the end of an array) leads to undefined results.