Running my program through valgrind, I'm getting an invalid read of size 4 error in the following code (I think at the line where fscanf is called)
Important Info: numIntegers
is the maximum number of integers that can be read, while numsInFile
specifies the amount of integers present in the file.
I use the minimum of the two to initialize the array. The reason for this is because if numIntegers
is 100
and there are 22
integers in the file, I only want an array of size 22
. If numIntegers is 22
and there are 100
integers in the file, I still want an array of size 22
since only 22
can be read.
Here is my code:
// Get number of integers (first number)
int numsInFile;
fscanf(fp, "%d", &numsInFile);
// find minimum of numstoread and numintegers and use that as counttouse
if(numsInFile < numIntegers)
countToUse = numsInFile;
else
countToUse = numIntegers;
// Initialize the integers array with the minimum value as well - since it will only store this many
integers = malloc(sizeof(int) * countToUse);
for(int i = 0; i < numsInFile; i++){
if(i < numIntegers){
int currInt;
if(fscanf(fp, "%d", &currInt) == 1)
integers[i] = currInt;
else
break;
}
else
break;
}
Any help is appreciated ahead of time. I can't for the life of me figure out why I'm getting this error in valgrind...
Code edited - No more errors
// Get number of integers (first number)
int numsInFile;
if( fscanf(fp, "%d", &numsInFile) != 1)
fprintf(stderr, "Error reading number of integers(first number) from file. Exiting.\n");
exit(1);
}
// find minimum of numstoread and numintegers and use that as counttouse
if(numsInFile < numIntegers)
countToUse = numsInFile;
else
countToUse = numIntegers;
// Initialize the integers array with the minimum value as well - since it will only store this many
integers = malloc(sizeof(int) * countToUse);
for(int i = 0; i < countToUse; i++){
int currInt;
if(fscanf(fp, "%d", &currInt) == 1)
integers[i] = currInt;
else{
fprintf(stderr, "Error loading integer array in countAndSort(). Exiting.\n");
exit(1);
}