函数用于不同的字符串后,字符串的值会神奇地改变

时间:2015-09-09 04:53:03

标签: c dbg

enter image description here

如此dbg调试日志中所示,在intToBinary(num1,string1)函数调用之后打印string1 = '0' <repeats 28 times>, "1000"。但随后在下一条指令中调用intToBinary(num2,string2)。如您所见,不同的参数传递给intToBinary函数。第二次使用不同的变量调用函数时,变量string1如何受到影响?在日志中,它表示第一个字符从0变为\(或\0?)。

这是必要时功能的pastebin。 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';
        }
    }
}

我只是不知道这里发生了什么。我尝试切换两个函数调用的顺序,因此它已更改为以下

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

奇迹般地,第一个字节保持'0',这就是我想要的。但现在我只是想知道为什么这一改变首先......

1 个答案:

答案 0 :(得分:2)

您尝试以32个字节存储32位二进制数;你忘了为null终止符分配一个额外的字节。当在string2之后写入null时,它会破坏string1的开头。

未定义的行为(在数组末尾写入)会导致未定义的结果。

相关问题