Joe Ducko
Joe Ducko

Reputation: 21

Segmentation fault while reading a file in C

Good evening! My goal right now is just making something small to read out the characters in a file of any type (and put them into a string for use later in the program) but I keep currently running into an issue where when I run the code and it segmentation faults at the line "input[n] = (char)c;" and I've tried troubleshooting by printing the characters and the value of n, and every time (despite me changing my malloc to different sizes) the printf statement will get halfway through the number "134510" or will print the character at offset 134509 before faulting at the line below. I would like to know what my issue is and how to fix it, as it's weird to me that the program is only able to get through about 10% of the file.

Thank you!!

int c = 0; //Counting the current character being read
int n = 0; //Counting the current character being written

char *input; //A string of all characters in the file

FILE *inputFile; //File to read

if(!(inputFile = fopen(argv[1],"r"))){  // Open in read mode
    printf("Could not open file");   // Print and exit if file open error
    return 1;
}

input = (char *)malloc(sizeof(inputFile) * sizeof(char));

while (1){  //Put all of the characters from the file into the string
    c = fgetc(inputFile);

    if(feof(inputFile)){ //If it reaches the end of the file, break the loop
        break;
    }

    printf("%c ", c); //Troubleshooting

    input[n] = (char)c;
    n++;
}

Upvotes: 1

Views: 942

Answers (3)

Eyal BD
Eyal BD

Reputation: 33

You don't have to know the file size in advance.

You can use the method described below:

  1. open the file
  2. allocate the result buffer
  3. read char
  4. if EOF then close file, append zero byte and return buffer.
  5. append char to buffer
  6. if end of buffer realloc with double buffer size.
  7. continue from 3

Upvotes: 0

Daniel Choi
Daniel Choi

Reputation: 194

The reason why you are segfaulting is because of this line:

input = (char *)malloc(sizeof(inputFile) * sizeof(char));

It may look right to malloc a size of the file; however, you are getting the size of the inputFile POINTER. This is totally different from the regular file, since pointers are only 4 bytes on most computers!

This means you are only allocating 4 bytes of data.

How do you avoid this?

Since you are only trying to read characters, you can simply:

while ((int)(result = getline(&line, &capacity, inputs)) != -1)

This will read the entire line and you can just put that line in to another char *.

Upvotes: 2

NPE
NPE

Reputation: 500883

The trouble is that sizeof(inputFile) does not return the size of the file. It returns the size — in bytes — of the FILE* pointer; the size of that pointer is completely unrelated to the size of the underlying file.

What you're looking for is discussed in How do you determine the size of a file in C?

Upvotes: 3

Related Questions