C 函数在不同的字符串上使用后,字符串的值会发生神奇的变化
如此dbg调试日志所示,C 函数在不同的字符串上使用后,字符串的值会发生神奇的变化,c,dbg,C,Dbg,如此dbg调试日志所示,string1='0',在intToBinary(num1,string1)函数调用后打印“1000”。但是在下一条指令中调用intToBinary(num2,string2)。如您所见,不同的参数被传递给intToBinary函数。为什么变量string1会受到第二次使用不同的变量调用函数的影响?日志中显示第一个字符从0变为\(或\0?) 这是函数的粘贴箱,以备不时之需 神奇的是,第一个字节保持为'0',这就是我想要的。但现在我只想知道为什么这会改变 字符串[32]='
string1='0',在intToBinary(num1,string1)函数调用后打印“1000”
。但是在下一条指令中调用intToBinary(num2,string2)。如您所见,不同的参数被传递给intToBinary函数。为什么变量string1
会受到第二次使用不同的变量调用函数的影响?日志中显示第一个字符从0变为\
(或\0
?)
这是函数的粘贴箱,以备不时之需
神奇的是,第一个字节保持为
'0'
,这就是我想要的。但现在我只想知道为什么这会改变 字符串[32]='\0'代码>
这会溢出您的输入缓冲区。我想你会发现你的string1
在内存中紧跟在string2
之后。因此,将string2
溢出1个字节将运行到string1
您试图在32个字节中存储32位二进制数;您忘记为空终止符分配额外的字节。当在string2
之后写入null时,它会关闭string1
的开头
未定义的行为(在数组末尾之外写入)会导致未定义的结果。使用所有警告和调试信息进行编译(gcc-Wall-Wextra-g
,如果使用)。使用调试器(gdb
)并设置观察点(使用gdb
的watch
命令)您可能应该阅读更多关于C编程的内容,了解什么是C编程,应该改为什么?我甚至应该分配空终止符吗?如果您想要字符串,那么当然必须NUL终止。只需将字符串缓冲区设置为33而不是32字节。
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);