Why don't I get a segmentation fault when I write beyond the end of an array?

后端 未结 4 1793
闹比i
闹比i 2020-11-22 10:11

why is this not giving error when I compile?

#include 
using namespace std;

int main()
{
    int *a = new int[2];
    // int a[2]; // even t         


        
4条回答
  •  忘掉有多难
    2020-11-22 10:31

    compilers with good code analysis would certainly warn on that code referencing beyond your array allocation. forgetting the multiple a declaration, if you ran it, it may or may not fault (undefined behavior as others have said). if, for example, you got a 4KB page of heap (in processor address space), if you don't write outside of that page, you won't get a fault from the processor. upon delete of the array, if you had done it, and depending on the heap implementation, the heap might detect that it is corrupted.

提交回复
热议问题