[英]Why is my program accessing values of the binaryString array when I try to print "value"?
#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] = '\0';
}
int main(void)
{
char value = 5;
char binaryString[6];
MakeBinaryString(binaryString, value);
printf("The binary equivalent of %d is %s\n", value, binaryString);
return 0;
}
Output:48的二進制等價物是00000101
因此,如果我們將 binaryString 數組的大小增加到 9,則可以修復上述代碼。但我不明白為什么將 value 打印為 48。如果我注釋掉 MakeBinaryString 的 else 塊,則 value 將打印為 5。但是else 塊,無論我將 char 值設置為什么值,它都會打印 48 或 49。
在您展示的代碼中,您在binaryString
的范圍之外編寫,當只有 6 個元素時訪問 9 個元素。這會調用未定義的行為,任何事情都可能發生。
在這種特殊情況下您看到48
或49
的原因是 memory恰好被布置成越界寫入破壞了value
。
'0'
和'1'
的數字 ASCII 值分別是48
和49
。 當你寫越界時,你就是用其中之一覆蓋value
。
請務必注意,您正在做的事情是不允許的,並且可能導致任何行為。 你很幸運,變量在堆棧上的組織方式使得唯一明顯的損害是value
。 為不同的平台構建,使用不同的編譯器或不同的編譯器選項,或者向程序添加更多內容可能會導致不同的任意結果,包括(但不限於)程序中使用的其他數據的崩潰和損壞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.