0

So today i was testing out some code for a university lab and i found out that when dynamically allocating an array of 6 integers in C++, is possible to read and write to the 7th and 8th positions of the dynamically allocated array (i.e., 6th and 7th index) as seen in the picture below.

Dynamically allocating an array of 6 integers - initialising 8 integers and printing 8 integers

Now of-course if i try replicate this with a static array i will receive a runtime error as expected.

So the question is, why does this work and what are some pitfalls when setting this in use?

MashRoofa
  • 103
  • 10
  • 3
    This is undefined behavior. One of the worst behaviors of UB is when your code appears to work but is broken. Related: [https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviours-that-a-c-programmer-should-know-a](https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviours-that-a-c-programmer-should-know-a) – drescherjm Mar 06 '22 at 16:06
  • Note that the duplicate (except for the answer mentioning stack-protector) applies whether you are using an array with automatic storage duration (what you call "static") or dynamic storage duration (`new`). – user17732522 Mar 06 '22 at 16:09
  • *i found out that when dynamically allocating an array of 6 integers in C++, is possible to read and write to the 7th and 8th positions of the dynamically allocated array* -- "I found out that when I dangle 600 pounds from a rope that is only rated to hold 500 pounds, the rope didn't break". That is basically what you're saying, and that in layman's terms, what undefined behavior is. That rope may hold forever, break tomorrow, break next week, another rope rated for 500 pounds may break immediately, etc. – PaulMcKenzie Mar 06 '22 at 16:36

0 Answers0