简体   繁体   中英

Why don't I get an error when I run the following code

I am running the following code where I declare a dynamic 2D array, and then go on to assign values at column indexes higher than the number columns actually allocated for the dynamic array. However, when I do this the code runs perfectly and I don't get an error, which I believe I should get.

 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;
    }

The link to the output I get is here (The values are actually assigned accurately, don't know why, though).

In C++, accessing a buffer out of its bounds invokes undefined behavior (not a trapped error, as you expected).

The C++ specification defines the term undefined behavior as:

behavior for which this International Standard imposes no requirements .

In your code, both

    bitarray[0][64] = '1';
    bitarray[10][64] = '1';

are accessing memory out-of-bound,. ie, those memory locations are "invalid". Accessing invalid memory invokes undefined behaviour .

The access violation error or segmentation fault is one of the many possible outcomes of UB. Nothing is guaranteed.

From the wiki page for segmentation fault ,

On systems using hardware memory segmentation to provide virtual memory, a segmentation fault occurs when the hardware detects an attempt to refer to a non-existent segment, or to refer to a location outside the bounds of a segment, .....

so, maybe, just maybe , the memory area for bitarray[0][64] is inside the allocated page (segment) which is accessible (but invalid anyway) by the program , in this very particular case. That does not mean it will be, always.

That said, void main() is not a correct signature of main() function. The recommended ( C++11 ,§3.6.1) signature of main() is int main(void) .

C++11 引入了std::array并且方法at()提供了越界检查。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM