-2

I have been playing around with file writing functions to study their properties in more detail, along with some other things as well (however what I was doing is ultimately irrelevant), and while I was doing that I encountered a segmentation fault. But not just the everyday type of segfault (dereferencing to unallocated space or something), the segfault is somehow caused by the declaration of a character array. In the code char name[10]. The declaration of char name[10] results in segmentation fault, and I do not understand why. Commenting this declaration removes the issue. What is going on here?

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;

}

Cœur
  • 37,241
  • 25
  • 195
  • 267
prcssngnr
  • 101
  • 2
  • Think about it this way if you don't get it! you are trying to build a home for someone who doesn't have land for constructing it on! Your str hasn't been allocated any space where it could store the information that would flow in! – Rahul Jha Sep 23 '15 at 22:29
  • In the `if(file == NULL)` case you actually need to abort instead of carrying on – M.M Sep 23 '15 at 23:17
  • You should check `cr != NULL` before doing `*cr` or using `str`. – M.M Sep 23 '15 at 23:18
  • How about first reading a C book or at least the man pages of the functions used? – too honest for this site Sep 23 '15 at 23:41

1 Answers1

3
 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.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Yeah allocating space for str worked, thanks. Although I don't understand why the code runs in the situation where no space is allocated and the name[10] array not commented. What does that have to do with anything? – prcssngnr Sep 23 '15 at 22:33
  • 1
    It's undefined behavior, anything can happen. – ouah Sep 23 '15 at 22:43