Search code examples
c++pointersvisual-c++undefined-behaviordynamic-memory-allocation

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).


Solution

  • 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.