Reputation: 1255
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));
?
Upvotes: 0
Views: 485
Reputation: 658
take care of youre data type
typedef struct myArray {
int count;
int maxCount;
int *numbers;
} myArray;
this means that count and maxcount are signed integers and they can reach negative values which is not correct for count and can lead also to some memory corruption.
Upvotes: 0
Reputation: 179402
You wrote past the end of the array.
while (scanf("%d", &randomNumbers.numbers[randomNumbers.count]) == 1) {
randomNumbers.count++;
if (randomNumbers.count > randomNumbers.maxCount)
randomNumbers = growMyArray(randomNumbers);
}
Because you use >
in the test, the if
only fires once randomNumbers.count = randomNumbers.maxCount + 1
, i.e. the scanf
writes to randomNumbers.numbers[randomNumbers.maxCount]
which is past the end of the array.
Therefore, change >
to >=
in the if
statement there.
Upvotes: 5