Search code examples
c++pointersdynamicsegmentation-faultdynamic-allocation

Segmentation fault in a program that reverses a dynamically allocated array


I was doing a test and the online test engine showing segmentation error, which is confusing because with no further details, and I checked the pointer no NULL and they work pretty fine, but don't how array here works. Because when debugging, everything is fine, until I try to cout/print out the array. it's reporting a is crushed here and break. I can do nothing here if it break, and I hit break or continue. if I continue, it runs just fine. so I was really confused.

My computer is windows 7, I run code in visual studio 2010 c++. Debugging is not that clear to solve the problem, and I am learning c++ not very efficient. Solve with Array need dynamic allocation.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void reverseArray(int size, int num[]) {
    if(size>1) {
        int *p = &num[size-1];
        int *f = num;
        for(int i = 0;i < size/2; i++){
            swap(*p, *f);
            p--;
            f++;
        } 
    }
}

int main() {
    int len;
    int a[len];/This is the bug, can't use uninitialized var assign array/
    cin >> len;
    for(int i = 0; i < len; i++){
        cin >> a[i];
    }
    reverseArray(len, a);
    for(int i = 0; i < len; i++){
        cout << a[i] << " ";
    }
    return 0;
}

This has something to with dynamic allocation, when I work in java, I create a new array. I have to

int[] newArray = {2,4,1,2,3};

or

int[] newArray = new int[] {2,4,1,2,3};

Finally, this problem is solved, which makes me very happy. Reading and learning is very important, coding is also important. Thanks all,

And using vector instead of using array. It would be easier.

#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
int main() {
    int a;
    int len;
    vector<int> myvector;
    cin >> len;
    for(int i = 0; i < len; i++){
        cin >> a;
        myvector.push_back(a);
    }
    reverse(myvector.begin(), myvector.end());
    for(int i = 0; i < len; i++){
        cout << myvector[i] << " ";
    }
    return 0;
}

Using Array again(I doubt the following code):

#include<iostream>
//#include<cstdlib>
using namespace std;

void reverseArray(int size, int nums[]){
    if(size > 1){
        int *p = &nums[size-1];
        int *q = nums;
        for(int i = 0; i< size/2; i++){
            swap(*p, *q);
            p--;
            q++;
        }
    }
}

int main(){
    int len;
    cin >> len;
    int *a = new int[len];//a point to the first ele.

    for(int i = 0; i< len; i++){
        cin >> a[i];
    }
    reverseArray(len, a);
    for(int i = 0; i < len; i++){
        cout << a[i] << " ";
    }
    delete [] a;
    return 0;

}

It worked perfect on my laptop, which is confusing because a is pointer, but I use it like an array. It shouldn't be working......

Final Array version: http://ideone.com/ZMsD35 Done perfectly.

#include<iostream>
using namespace std;

int main(){
    int len;
    cin >> len;
    int *a = new int[len];
    for(int i = 0; i< len; i++){
        cin >> a[i];
    }
    reverse(a, a+len);
    for(int i = 0; i< len; i++){
        cout << a[i];
    }
    delete [] a;
    system("pause");
    return 0;

}

Solution

  • The most likely reason for a segfault is the input. When the testing software passes len of size sufficient to overflow the automatic storage area, your program crashes on this line:

    int a[len];
    

    The exact value of len is system-dependent, but an input of 1,000,000 should do it on most common systems.

    The fix is really straightforward - replace the declaration with

    int a* = new int[len];
    

    This will place the data in dynamic memory, rather than the automatic memory. It will also make your program standard-compliant, because variable-length arrays in C++ are an extension to standards.

    Don't forget to delete a once you are done to avoid memory leak:

    delete[] a;