[英]What's the difference in following code, when I use parentheses I get expected result but random number if I don't use the parentheses
[英]Why don't I get an error when I run the following code
我正在運行以下代碼,其中我聲明了一個動態 2D 數組,然后繼續在高於實際分配給動態數組的列數的列索引處分配值。 但是,當我這樣做時,代碼運行得很好,我沒有收到錯誤,我相信我應該得到。
void main(){
unsigned char **bitarray = NULL;
bitarray = new unsigned char*[96];
for (int j = 0; j < 96; j++)
{
bitarray[j] = new unsigned char[56];
if (bitarray[j] == NULL)
{
cout << "Memory could not be allocated for 2D Array.";
return;// return if memory not allocated
}
}
bitarray[0][64] = '1';
bitarray[10][64] = '1';
cout << bitarray[0][64] << " " << bitarray[10][64];
getch();
return;
}
我得到的輸出鏈接在這里(這些值實際上是准確分配的,但不知道為什么)。
在 C++ 中,訪問緩沖區超出其邊界會調用未定義的行為(不是您預期的捕獲錯誤)。
C++ 規范將術語未定義行為定義為:
本國際標准未規定要求的行為。
在您的代碼中,兩者
bitarray[0][64] = '1';
bitarray[10][64] = '1';
正在訪問內存越界,。 即,那些內存位置是“無效的”。 訪問無效內存會調用未定義的行為。
訪問沖突錯誤或分段錯誤是 UB 的眾多可能結果之一。 什么都不能保證。
在使用硬件內存分段來提供虛擬內存的系統上,當硬件檢測到嘗試引用不存在的段或引用段邊界之外的位置時,會發生段錯誤,......
所以,也許,只是也許, bitarray[0][64]
的內存區域在分配的頁面(段)內,在這個非常特殊的情況下,程序可以訪問(但無論如何都是無效的)。 這並不意味着它會一直如此。
也就是說, void main()
不是main()
函數的正確簽名。 main()
的推薦( C++11
,§3.6.1)簽名是int main(void)
。
C++11 引入了std::array並且方法at()
提供了越界檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.