简体   繁体   中英

Segmentation fault in a simple insertion sort?

Why this code waits for user to input 10 integers when size of array input by user is 8 ? It gives segmentation fault when 10 integers are used.`

#include <iostream>
using namespace std;
int main()
{
    int x, a[x];
    cout << "enter the size of array" << endl;
    cin >> x;
    cout << "enter the elements" << endl;
    for (int j = 0; j < x; j++)
        cin >> a[j];
    for (int i = 1; i < x; i++) {
        for (int k = 0; k < i; k++) {
            if (a[i] < a[k])
                swap(a[i], a[k]);
            else
                continue;
        }
    }
    for (int m = 0; m < x; m++)
        cout << a[m];
}

The issue is in these lines:

int x, a[x];
cout<<"enter the size of array"<<endl;
cin>>x;

Here, when you declare the array a , it sizes it using the value stored in x . However, at this point, you haven't given x a value, so you get an array of garbage size. Reading in x later on doesn't retroactively resize the array (the same way that changing a variable at one point doesn't retroactively change other variables whose value is based on it), so the array size doesn't match the read value. Plus, if the array is too big, you might get a stack overflow before you even get to the spot where you read things!

To fix this, consider using something like std::vector rather than raw arrays. (As a note, variable-length arrays aren't supported in C++, so using std::vector would be more portable.)

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