Why don't I get a segmentation error when I write outside the array?

Why does this not give a compilation error?

#include <iostream>
using namespace std;

int main()
{
    int *a = new int[2];
    // int a[2]; // even this is not giving error
    a[0] = 0;
    a[1] = 1;
    a[2] = 2;
    a[3] = 3;
    a[100] = 4;
    int b;

    return 0;
}

can someone explain why this is happening. Thanks in advance.)

+5
source share
4 answers

I assume that you come from a Java or Java-like language, where when you exit the bounds of the array, you get the exception "index index out of bounds".

Well, C expects more from you; it saves the space that you ask for, but it does not check whether you go beyond this accumulated space. Once you do this, as indicated above, the program has such a scary undefined behavior.

, , , /​​ , , , " " .

+2

undefined == . , , .

a - .

+9

, a, , ; , . , , , .

. , , . , ++, , . , undefined, , , .

, . , . . , , , .

, std::vector at(). , . , .

+8
source

compilers with good code analysis will probably warn that the code is referenced outside of your array distribution. forgetting the multiple declaration, if you ran it, it may or may not be an error (undefined behavior, as others have said). if, for example, you have a page with a heap of 4 Kbytes (in the address space of the processor), if you do not write outside this page, you will not receive an error from the processor. after deleting the array, if you did, and depending on the implementation of the heap, the heap may find that it is damaged.

0
source

All Articles