R.mia R.mia - 5 days ago 6
C++ Question

(about pointer or creating array)segmentation error or dynamic allocation arrays in C++

I was coding in hackerrank and practicing my c++, but can't pass the submission. showing segmentation error.Really confused about the error and I checked the pointer no NULL and they work pretty fine, but don't how array here works.

#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++;
}
}
}
void swap(int &a, int &b){
int tmp = a;
a = b;
b = tmp;
}
int main() {
int len;

int a[len];
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};

Answer

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;
Comments