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

后端 未结 4 1709
闹比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:46

    I'm guessing you're coming from Java or a Java-like language where once you step out of the boundary of an array, you get the "array index out of bounds" exception.

    Well, C expects more from you; it saves up the space you ask for, but it doesn't check to see if you're going outside the boundary of that saved up space. Once you do that as mentioned above, the program has that dreaded undefined behavior.

    And remember for the future that if you have a bug in your program and you can't seem to find it, and when you go over the code/debug it, everything seems OK, there is a good chance you're "out of bounds" and accessing an unallocated place.

提交回复
热议问题