简体   繁体   中英

C++ program crashes on iterating till the last element of an array

I have the following code:

int main()
{
    int a[5];

    for (int i = 0; i <= 5; i++) {
        cin >> a[i];
    }

    for (int i = 0; i <= 5; i++) {
        cout << a[i] << endl;
    }
}

The program is supposed to take 6 integers as input and just print them to the output. It works fine for the first five integers but crashes while printing the sixth. As far as I know, in c++ an array defined "a[5]" should have 6 elements since it starts from 0, right? What's causing the crash?

int a[5];

is an array of 5 integers! The indexing is 0 , 1 , 2 , 3 , 4 .

The reason for this is how the elements live in memory. The index tells you how many spots to jump from the start of the array. So the first element, you have to jump 0 spaces, because it is at the very front of the array. The second element, you have to jump 1 space. Get it?

array start       |data|data|data|data|data|<nothing here!>
offset from start |   0|   1|   2|   3|   4| not allowed!!

So by trying to jump into a position that doesn't actually exist in the array, you cause Undefined Behaviour . This means your program is garbage. There is no guarantee at all what might happen. It might crash, or worse, it might appear to work, because you actually hit some memory that is really being used to store a completely different object. Then you end up with some really crazy behaviour that is hard to debug.

A loop over an array should look like this:

for (size_t i = 0; i < arraySize; ++i) // ...
                     ^ always <, never <=

But it is better to use std::vector , which will grow to the size you need, and manage all the memory for you. Then you can use myVector.at(3); to access the data, and it will throw an exception if you make a mistake like you did above. Or better, use the "range-based for loop", which will pull out all the elements for you:

#include <vector>
#include <iostream>

int main()
{
    const std::size_t howMany = 6; // how many ints to read
    std::vector<int> data;

    while (data.size() < howMany) { // haven't read enough yet
        int tmp = 0;
        std::cin >> tmp;
        if (!std::cin) { // somehow reading went wrong!
            return 1; // exit the program with an error code
        }
        data.push_back(tmp); // store the value we just read
    }

    for (int i : data) { // go through all the stored ints
        std::cout << i << '\n';
    }
}

(Also, see here for some common beginner mistakes you are making).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM