Tee Pee
Tee Pee

Reputation: 73

How to use fscanf for reading files in c(Segmentation Fault)?

I'm new user in stackoverflow. I wrote this code in c and I have no problem and the output is correct.

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char *str[10];
   FILE * fp;

   fp = fopen ("file.txt", "w+");
   fputs("We\nare\nin\n2016", fp);

   rewind(fp);

   fscanf(fp, "%s", str[0]);
   fscanf(fp, "%s", str[1]);              

   printf("Read String1 |%s|\n", str[0] );
   printf("Read String2 |%s|\n", str[1] );

   fclose(fp);

   return(0);
}

but when I use char *str[15] instead of char *str[10], the result is segmentation fault. What is wrong?

Upvotes: 2

Views: 168

Answers (2)

galmos
galmos

Reputation: 36

Keep in mind you are declaring char * str[10], you are reserving memory for ten pointers but you didn't call malloc to reserve memory for the contents of these pointers.

Your example seems similar to this tutorial of the function fscanf, http://www.tutorialspoint.com/c_standard_library/c_function_fscanf.htm.

But there, string parts are declared as char[10] instead of char *[10] which means they already have memory reserved for 10 characters. In this same example reading a string with length greater than 10 will also generate problems.

Upvotes: 0

P.P
P.P

Reputation: 121407

The pointers str[0] and str[1] are uninitialized. So, your program has undefined behaviour.

Either you need to allocate using malloc() or make them an array of arrays (e.g. str[2][256];) with fixed length that's sufficient enough for the strings you read from the file. In any case, I'd personally use fgets() instead of fscanf() and then parse the line as necessary.

It would also help to do error checking for all functions (fopen(), fscanf(), etc).

Upvotes: 1

Related Questions