I've debugged the heck out of this and cannot figure why my fgets is not working. Before I changed my code such that it dynamically resizes arrays, fgets works perfectly well. As I am a beginner in C, this problem has baffled me for quite a long time.
Here is the faulty code:
int readNumbers(int **array, char* fname, int hexFlag) {
int numberRead = 0;
FILE* fp;
int counter = 0;
char arr[100];
char* ptr;
size_t curSize = 16;
int radix = hexFlag ? 16 : 10;
*array = malloc(0 * sizeof(*array));
fp = fopen(fname, "r");
if (fp == NULL) {
printf("Error opening file\n");
return -1;
}
while (fgets(arr, sizeof(arr), fp)) { //Seg faults here when it reaches end of file.
ptr = strtok(arr, " \n");
while(ptr) {
if (counter >= curSize) {
curSize += 16;
array = realloc(*array, curSize * sizeof(**array));
}
(*array)[counter++] = strtol(ptr, NULL, radix);
++numberRead;
ptr = strtok(NULL , " \n");
}
}
if (ferror(fp)) {
fclose(fp);
return -1;
}
Here is the working code before the changes to make the array resize:
int readNumbers(int array[], char* fname, int hexFlag) {
int numberRead = 0;
FILE* fp;
int counter = 0;
char arr[100];
char* ptr;
fp = fopen(fname, "r");
if (fp == NULL) {
printf("Error opening file\n");
return -1;
}
while (fgets(arr, sizeof(arr), fp)) {
ptr = strtok(arr, " \n");
while(ptr) {
if (hexFlag == 0) {
array[counter++] = strtol(ptr , NULL , 10);
} else {
array[counter++] = strtol(ptr, NULL, 16);
}
++numberRead;
ptr = strtok(NULL , " \n");
}
}
if (ferror(fp)) {
fclose(fp);
return -1;
}
The newly added changes seg faults when the end of file is reached. I strongly suspect that this has to do with the double pointers. Any help is strongly appreciated!
I haven't gone through the whole code but *array = malloc(0 * sizeof(*array))
here this malloc
call will not allocate any memory.