When I go beyond the border of the array, I do not get an error, but if I try to delete by the pointer, the program crashes. Why?

int main() { int * p = new int[5]; p[10] = 5; delete [] p; } 
  • one
    after p[10] = 5; the program can behave as it pleases, it is called UB. Fall, respectively, can at an arbitrary point in time. - andy.37
  • one
    "but not when going beyond the bounds of the array" - and this is what you write, personally going beyond these same bounds ??? - PinkTux
  • @PinkTux: I think the vehicle meant that it does not fall at the time of going abroad. - VladD
  • C does not control your actions for you. There are no checks to go abroad. You just wipe some area of ​​memory, and that because of this will happen is impossible to predict. - Mike

2 answers 2

You can spoil the service information of the memory manager, that's all. As a result, the memory manager is not able to correctly free up memory, and the system crashes.

Undefined behavior is so vague :). By the way, I recommend the book Safe Programming in C and C ++ - there is much to say about this (incorrect work with memory, which may be a vulnerability).

    Because the indefinite behavior that occurs when writing outside the allocated memory can manifest itself quite differently. Including at later operations. This is the essence of UB (Undefined Behavior).