1

I'm trying to read in a string of text from a FILE*, but every time I try I get a segmentation fault. This is the only thing I'm doing in the program, so I'm not really sure why this is happening.

#include <stdio.h>

int main(){
  FILE* file;
  char* string;
  file = fopen("practice.txt", "r");
  fgets(string, 100, file);
  printf("%s", string);
  return 0;
}
1
  • 2
    Please check for "file = fopen() == NULL". OK? ;) After that, please make sure you've allocated space for "fgets()" to read something into. "char string[80]" and "fgets (string, sizeof(string), file)" will work
    – paulsm4
    Oct 2, 2012 at 20:17

4 Answers 4

6

You haven't allocated any memory for your string. You can use malloc to allocate memory for your string, or use an array char string[100];

2
  • 1
    I changed it to char string[100] and now it works. Thanks for the help. Oct 2, 2012 at 20:23
  • @nh0815 - Be sure to check if "fopen()" fails. And I'd strongly urge you to use a #define and/or "sizeof()" to make sure the #/bytes you allow in fgets ("100") always matches the #/bytes in your buffer ("string[100]"). IMHO...
    – paulsm4
    Oct 2, 2012 at 21:01
3

Be sure to allocate memory to store what you're going to read:

char string[101];
1

That is because the string is uninitialized. string is a char * and initially holds garbage value as an address, which is dereferenced by the fgets function, resulting in undefined behaviour.

Either do

char string[BUFFER_LEN];

And define BUFFER_LEN appropriately

or do

char *string;
string = malloc (sizeof (char) * buf_siz);

where buf_siz holds the length of the buffer. When you dynamically allocate the string, remember to free (string) when you have finished working with the memory block allocated with malloc, it is a good practice, and will prevent memory leak in larger programs.

Always check if the file was opened successfully by checking the return value of fopen . If it returns NULL then the open operation failed. Else it will return the FILE pointer.

1

char *string declares a pointer, but doesn't set it to point anywhere meaningful; you haven't allocated any memory to store the text read from the file.

You either need to allocate an array, like so:

char string[101] = {0}; 
...
fread(string,100,file);
printf("%s\n", string);

or allocate the memory at runtime:

char *string;
...
string = calloc(101, sizeof *string);
if (string)
{
  fread(string,100,file)
  printf("%s\n", string);
  free(string);
}

In both cases we allocate enough memory for 101 characters to account for the 0 terminator, and since fread won't write a 0 terminator to the end of the input, we initialize the memory to all-bits-zero in both cases (the first by using an initializer, the second with the call to calloc).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.