为什么当我尝试打印"值"时,我的程序访问 binaryString 数组的值?

  • 本文关键字:程序 访问 binaryString 数组 打印 c
  • 更新时间 :
  • 英文 :

#include <stdio.h>
#include <math.h>
void MakeBinaryString(char *outString, char valueToConvert)
{
// Convert a 1-byte value to a string that shows its value in
// binary. We do this by checking to see each bit is on and
// if it is, setting the character value to '1' or '0' if not.
for (int i = 0; i < 8; i++)
{
// Is the bit a 1?
// The shifting is needed to quickly generate a power of 2
// so that we check only 1 bit at a time, starting with bit 7 // and working its way down.
if (valueToConvert & (1 << (7 - i)))
outString[i] = '1';
else
outString[i] = '0';
}
outString[8] = '';
}
int main(void)
{
char value = 5;
char binaryString[6];
MakeBinaryString(binaryString, value);
printf("The binary equivalent of %d is %sn", value, binaryString);
return 0;
}

输出:48的二进制等价物是00000101

因此,如果我们将binaryString数组的大小增加到9,则可以修复上面的代码。但我不明白为什么值被打印为48。如果我注释掉MakeBinaryString的else块,则值将打印为5。但对于其他块,无论我将char值设置为什么值,它都是打印48或49。

在您显示的代码中,您在binaryString的边界之外进行编写,在只有6个元素的情况下访问9个元素。这会调用未定义的行为,任何事情都可能发生。

您在这种特殊情况中看到4849的原因是内存恰好被布置为越界写入正在损坏value

'0''1'的ASCII数值分别为4849。当您写越界时,您正在用其中一个重写value


重要的是要注意,你所做的事情是不允许的,并且可能导致任何行为。幸运的是,变量在堆栈上的组织方式使得唯一明显的损坏是value。使用不同的编译器或不同的编译器选项为不同的平台构建,或向程序添加更多内容,都可能导致不同的任意结果,包括(但不限于(程序中使用的其他数据的崩溃和损坏。

相关内容

最新更新