0

I am scanning a string from a file and storing it into an array of strings. When I compile my program, it does not produce any error but when I run it, it says Segmentation fault (core dumped). I know that the error is in the fscanf statement, but I can't figure out what's wrong.

My code looks like this:

 FILE    *stringsIn = fopen("strings.txt", "rt");
 char    *strings[INPUT_STRINGS];

    for (int i = 0; i < INPUT_STRINGS; i++)
            fscanf(stringsIn, "%s ", &strings[i][0]);
pi3.14
  • 53
  • 1
  • 1
  • 6
  • A string is a null terminated array of *characters*. The only atrray you have in your program is an array of *pointers*. For a pointer to be usable in functions like `fscanf`, it needs to *point somewhere*. – n. m. could be an AI Feb 06 '19 at 06:46

1 Answers1

0

You have an array of pointers but you didn't allocate space for each string. In this case what you can do is preallocate a big enough buffer or read in a preallocated buffer, see how many characters were read and allocate a string of that size.

FILE    *stringsIn = fopen("strings.txt", "rt");
char    *strings[INPUT_STRINGS];

for (int i = 0; i < INPUT_STRINGS; i++) {
   strings[i] = (char*)malloc(2048); //allocate a big enough buffer
   fscanf(stringsIn, "%2047s ", &strings[i][0]);
}

The second version is something like:

FILE    *stringsIn = fopen("strings.txt", "rt");
char    *strings[INPUT_STRINGS];
char temp[2048];

for (int i = 0; i < INPUT_STRINGS; i++) {
   fscanf(stringsIn, "%2047s ", &temp);
   size_t len = strlen(temp);
   strings[i] = (char*)malloc(len + 1);
   strncpy(strings[i], temp, len);
}

Cristian Bidea
  • 679
  • 4
  • 12
  • 1
    Never use `"%s"` without specifying a width to limit the number of characters to read. *`malloc(len)`* off-by-one. – Swordfish Feb 06 '19 at 07:28
  • 1
    "*`strncpy(strings[i], temp, len);`*": Why not just `strcpy(strings[i], temp)`?! `strnpcy()`'s usage is so error prone, you should yourself in the foot so easyly, as the code you show unfortunately demonstrates. – alk Feb 06 '19 at 07:48
  • Also: Do not cast the result of `malloc()` & friends in C. – alk Feb 06 '19 at 07:49
  • I dont understand why there is a (char *) before malloc. Can you please explain it? – pi3.14 Feb 06 '19 at 13:06
  • http://www.cplusplus.com/reference/cstdlib/malloc/ in the documentation it says that malloc returns void*, so i cast the result to char*. I think that some newer compilers don’t need that. – Cristian Bidea Feb 06 '19 at 15:38