1

While debugging I found an error with an int array of 0. In a test document I messed around with array with more cell input than their length.

int array[0];
for(int i = 0; i < 10; i++)
    array[i] = i;
for(int i = 0; i < 10; i++)
    cout << array[i];

After I compiled and ran the program I got

0123456789

Then I received the message "test.exe has stopped working". I expected both of these, but what I am confused about is why the compiler lets me create an array of 0, and why the program doesn't crash until the very end of the program. I expected the program to crash once I exceeded the array length.

Can someone explain?

Towell
  • 180
  • 1
  • 7
  • 8
    Welcome to [Undefined Behavior Land](http://en.wikipedia.org/wiki/Undefined_behavior). – NathanOliver Mar 17 '15 at 16:20
  • 3
    The language doesn't allow zero-size arrays. If you're not getting at least a warning from the compiler about the extension, then you need to turn up your warning level. – chris Mar 17 '15 at 16:21
  • Why your compiler quietly allows a zero-sized array? Your compiler is either broken or it is not a C++ compiler at all. – AnT stands with Russia Mar 17 '15 at 16:25

1 Answers1

0

The compiler should have at least warned you about a zero size array - if it didn't .. consider changing compiler.

Remember that an array is just a bit of memory just like any other. In your example the array is probably stored on the stack and so writing off the end of it may not cause much of a problem until your function exits. At that point you may find you have written some text over the return address and you get an exception. Writing off the end of arrays are a common cause of bugs in C/C++ - just be thankful you got an error with this one and it didn't just overwrite some other unrelated data.

Rob
  • 3,315
  • 1
  • 24
  • 35