I am reading integers from a file, and when I try to grow my array, I am getting a segmentation fault on the second call to growMyArray(struct myArray), specifically at int *grownArray = malloc(arrayToGrow.maxCount * sizeof(int));:
struct myArray growMyArray(struct myArray arrayToGrow) {
arrayToGrow.maxCount *= 2;
int *grownArray = malloc(arrayToGrow.maxCount * sizeof(int));
int i;
for (i = 0; i < arrayToGrow.count; i++)
grownArray[i] = arrayToGrow.numbers[i];
free(arrayToGrow.numbers);
arrayToGrow.numbers = grownArray;
return arrayToGrow;
}
My structure:
typedef struct myArray {
int count;
int maxCount;
int *numbers;
} myArray;
Reading from input redirection:
struct myArray getRandomNumbers() {
struct myArray randomNumbers;
randomNumbers.count = 0;
randomNumbers.maxCount = DEFAULT_SIZE;
randomNumbers.numbers = malloc(randomNumbers.maxCount * sizeof(int));
while (scanf("%d", &randomNumbers.numbers[randomNumbers.count]) == 1) {
randomNumbers.count++;
if (randomNumbers.count > randomNumbers.maxCount)
randomNumbers = growMyArray(randomNumbers);
}
return randomNumbers;
}
I find this particularly odd because growing the array always works the first time but never works the second time. I have used multiple values for DEFAULT_SIZE, ranging from 2 to 20000 on a set of test data of size 200000.
Is there an apparent reason why I am getting a segmentation fault on the second call to growMyArray, specifically at int *grownArray = malloc(arrayToGrow.maxCount * sizeof(int));?
You wrote past the end of the array.
Because you use
>in the test, theifonly fires oncerandomNumbers.count = randomNumbers.maxCount + 1, i.e. thescanfwrites torandomNumbers.numbers[randomNumbers.maxCount]which is past the end of the array.Therefore, change
>to>=in theifstatement there.