I have been playing around with file reading and writing functions and I encountered a segmentation fault. It seems to be related to reading from a file using gets. Below is the code I wrote.
The code I wrote is given below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc, char *argv[]){
//char name[10];
//strcpy(name, "George");
//printf("%s\n", name);
//if(argc == 2){
//char *myname = "George";
FILE *file = fopen("Readmystuff" , "rt");//fopen(argv[1],"rt");
if(file == NULL)
printf("Could not open file: %s\n", strerror(errno));
char *str, *cr;
int maxsize = 200;
cr = fgets(str, maxsize, file);
int fcl = fclose(file);
printf("\n");
int strl = strlen(str);
if(fcl == 0)
printf("File closed succesfully\ncr: %c\nstr: %s\nTotal string size - 1 (for null): %i\n", *cr, str, strl);
else
printf("File did not close");
//}
//else
//printf("There must be one argument, argv[1] = the filename, for the code to work\n");
return 0;
}
char *str, *cr;
/* ... */
cr = fgets(str, maxsize, file);
Your str
pointer is not initialized, its value is indeterminate. You are writing to an invalid object. Either define an array with a sufficient size or use malloc
to allocate one.