I'm trying to use fgets() to read text from a file and I keep getting a segmentation fault. The program reads in the entire file and then after it reads the last line it crashes. Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *readFile(FILE *);
char *readFile(FILE *file){
int *outputSize = (int *)malloc(sizeof(int));
(*outputSize) = 1024;
char *buf = (char *)malloc(sizeof(char)*1024);
char *output = (char *)malloc(sizeof(char)*(*outputSize));
*output='\0';
while(fgets(buf,1024,file)){
if(strlen(output)+strlen(buf)+1>(*outputSize)){
printf("REALLOCATING...");
(*outputSize) *=2;
output = realloc(output,sizeof(char)*(*outputSize));
}
printf("BUFFER SIZE: %d\nBUFFER : %s\n",strlen(buf),buf);
strcat(output,buf);
printf("OUTPUT SIZE: %d\nOUTPUT: %s\n",strlen(output),output);
}
printf("FREEING...");
free(outputSize);
free(buf);
return output;
}