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;
}
char *output = (char *)malloc(sizeof(char)*(*outputSize));*output=0; - BLUEPIXYif(strlen(output)+strlen(buf)+1>(*outputSize)){- BLUEPIXYmallocdoes not clear the memory, so putting a'\0'in the first character guarantees that the firststrcatwill work correctly. If you got lucky and had an initial 0 inoutput, then you won't have noticed the problem. If the lastprintf(...,output);looks right, then the crash isn't in the code you've posted. - user3386109if(strlen(output)+strlen(buf)+1>(*outputSize)){-->while(strlen(output)+strlen(buf)+1>(*outputSize)){although given code's logic, 1 pass should be enough. Just adding some defensive coding. - chux - Reinstate Monica