Array overflow (why does this work?)

14,336

Solution 1

It's undefined behavior. UB comes in many flavors. Here are a few:

1) It will kick your dog.

2) It will reformat your hard drive.

3) It will work without a problem.

In your case, with your compiler and on your platform and on this particular day, you are seeing (3). But try it elsewhere, and you might get (1), (2), or something else completely (most likely an access violation).

Solution 2

C/C++ does not do boundary checking when using arrays.

Since you are declaring a stack based array. Accessing outside the bounds of the array will just access another part of already allocated stack space.

So basically when you access something that is out of bounds, it won't throw a segmentation fault unless its completely out of your stack memory.

C/C++ is dangerous with array boundaries remember that!

Solution 3

The stack is very large. On Windows, it's 1 MB.

Since the program doesn't do much, the array would have been allocated close to the beginning of the stack. This means there would be almost 1 MB of empty space between the end of the array and the end of the stack.

So what does this mean? When you write past the end of the array, you're just clobbering your own stack space, not other programs', so the OS doesn't stop you and the program continues to run.

Share:
14,336
Nathan
Author by

Nathan

Third generation programmer.

Updated on October 20, 2022

Comments

  • Nathan
    Nathan over 1 year

    Okay, so I was teaching my girlfriend some c++, and she wrote a program that I thought wouldn't work, but it did. It accesses one more element in the array then there is (for instance, accessing array[5] for an array of size 5). Is this an instance of a buffer overflow? My thoughts on it are that it's writing to/accessing the memory directly after the array, is this correct? Basically my question here is..why does this work?

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    int size;
    
    cout << "Please enter a size for the array." << endl;
    cin >> size;
    cout << endl;
    
    cout << "There are " << size << " elements in this array." << endl;
    cout << endl;
    cout << endl;
    cout << endl;
    
    int array[size];
    
    for (int counter = 1; counter <= size; counter++)
    
    {
        cout << "Please enter a value for element " << counter << "." << endl;
        cin >> array[counter];
    
    }
    
    cout << endl;
    cout << endl;
    
    
    for (int counter = 1; counter <= size; counter++)
    
    {
        cout << "Element " << counter << " is " << array[counter] << "." << endl;
        cout << endl;
    
    }
    
    cout << "*bing! :)" << endl;
    cout << endl;
    
    
    return 0;
    }