I am trying to read a file that can be empty or can contain numbers into a dynamic array. And I am getting segmentation fault after it reads all the numbers in the file, or the file is empty and I am not sure why, it is doing that.
//ptr and fp are passed from another function
ptr = malloc(10 * sizeof(int));
if (ptr == NULL){
printf("failed to allocate memory\n");
}
int sz = 10;
int counter = 0;
int fnum;
int *temp;
char lp1[MAXLINE];// maxline is 100
int i = 0;
while(fgets(lp1, MAXLINE, fp)!= NULL){
if(counter >= sz){
sz *=2;
temp = realloc(ptr,sz);
if (temp == NULL) {
printf("failed to allocate memory\n");
}
if (temp != NULL){
ptr = temp;
//free(temp);
}
}
int len = strlen(lp1);
if (len > 0 && lp1[len-1] == '\n'){
lp1[len-1] = 0;
}
fnum = strToInt(lp1);// number from file
printf("%i value of lp1 \n", fnum);
ptr[i] = fnum;
i++;
counter++;
}
return sz;