2

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?

3
  • 1
    And where does each pointer in the str array point? Just because a program with undefined behavior seems to work doesn't mean it's correct. Commented Aug 22, 2016 at 11:05
  • And why this is correct for str[10]? I also initialized the str[15], but not work Commented Aug 22, 2016 at 11:10
  • 1
    It's not correct for e.g. char *str[10], it's just pure luck it seems to work (good or bad luck is a question of perspective). It just seems to work, you will still overwrite some memory seemingly randomly. Remember, one of the possible symptoms of undefined behavior is that it actually works, unfortunately. Commented Aug 22, 2016 at 11:14

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

And why this is correct for str[10]? I also initialized the str[15], but not work
char *str[10] is an array of pointers and those pointers are not initialized. They don't point at any memory you could write into. So you need to initialize with something like: str[0] = malloc(256); str[1] = malloc(256); (or use arrays as said in the answer).
0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.