Joseph Joseph - 20 days ago 7
C++ Question

Segmentation fault when passing a pointer to an array into a function (C++)

I'm trying to get a large array of random numbers, then pass that array into a function that will create a new array with 10 elements whose values correspond with the values in the large array. I pass the parameter start into the function to indicate the index of the large array from which I will start copying the values into the smaller array.

In case my explanation isn't clear, I have an array A of 20 randomly generated numbers:

A = {1, 2, 3, .... 20}

I want to make an array B that holds the first 10 numbers:

B = {1, 2, 3, .... 10}

and an array C that holds the second 10:

C = {11, 12, 13, .... 20}

I'm able to generate the random numbers and display them with a for loop, but once I start trying to make the new arrays I get a segmentation fault in terminal:

Segmentation fault (core dumped)

Below is my code.


int main() {

int size = 20;
int *arrA = getRandomScores(size);

int *arrB = applyScores(arrA, 0);
int *arrC = applyScores(arrA, 10);

for(int i = 0; i < 10; i++) {
cout << arrB[i] << endl;
}
cout << endl << endl;
for(int i = 0; i < 10; i++) {
cout << arrC[i] << endl;
}

return 0;
}

int *applyScores(int *arr, int start) {
int *newArr;

for(int i = 0; i < 10; i++) {
newArr[i] = arr[start];
start++;
}

return newArr;
}

int *getRandomScores(int size) {
int *arr;

//return null if size is zero or negative
if (size <= 0)
return NULL;

//dynamically allocate the array
arr = new int[size];

//seed the random number generator
srand(time(0));

//populate the array with random numbers
for(int i = 0; i < size; i++)
arr[i] = rand() % 100;

return arr;
}


I'm on linux, so I was told to use valgrind to see a more detailed error message. Below is what valgrind gave me. This is my first encounter with a segmentation fault, so forgive me if the answer is trivial with valgrind's help.

valgrind error log screenshot

Answer

You declare newArr as a pointer to int, but it points nowhere. You could create a new array like this:

int *newArr = new int[10];

but remember to delete the array when you are done with it:

delete[] arrB;
delete[] arrC;

Or you could simply use std::vector<int> for your arrays A,B and C (or at least B and C).