-1

I'm working on dynamic arrays for my c++ course, but I'm confused about the behavior of my dynamic arrays. For example, if I run this code:

int* myDynamicArr = new int[3];

for (int i = 0; i < 10; i++)
{
    myDynamicArr[i] = i + 1;
    cout << myDynamicArr[i] << endl;
}

I would expect it to not work since I only declared it as size 3. But when I run it, it prints out 0-9. Same thing if I do this:

char* myCharArr = new char[2];
strcpy(myCharArr, "ThisIsALongString");
cout << myCharArr;

It prints the full string even though it seems like it should fail. Can anyone explain what I'm doing wrong here? Thanks!

Nick
  • 3
  • 2
  • 1
    Welcome to the world of "Undefined Behavior" [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/a/4105123) – 001 Oct 27 '21 at 20:35

1 Answers1

2

C++ does not perform bounds checking on arrays. So when you read or write past the bounds of an array you trigger undefined behavior.

With undefined behavior, your program may crash, it may output strange results, or it may (as in your case) appear to work properly.

Just because it could crash doesn't mean it will.

dbush
  • 205,898
  • 23
  • 218
  • 273