Search code examples
csegmentation-faultdynamic-arraysscanf

Using fscanf to input data into a dynamic struct pointer array?


I have an assignment and have run into somewhat of a snag. The following code is supposed to take input from a file, read it into a struct that I have defined, and do so without any limit to the number of input lines. However, it segfaults at line 24:

1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 typedef struct __student {
6         int ID;
7         char fname[33];
8         char lname[33];
9         float grade;
10 } student;
11
12 void partA(FILE *fp) {
13
14         int i, r;
15         i = r = 0;
16         int N = 1000;
17         student **S;
18
19         S = (student **)malloc(sizeof(student *) * N);
20
21
22         while(!feof(fp)){
23                 fscanf(fp, "%d %[^,], %s %f", &S[i]->ID, S[i]->lname, S[i]->fname, &S[i]->grade ); // segfault occurs on this line
24                 printf("%d %s %s %f\n", S[i]->ID, S[i]->fname, S[i]->lname, S[i]->grade);
25                 i++;
26                 printf("Something's happening, at least");
27                 if(i == N){
28                         N *= 2;
29                         S = (student **)realloc(S, sizeof(student) * N);
30                         if(S == NULL) {
31                                 printf("Memory reallocation failed; Fatal error.");
32                                 break;
33                         }
34                 }
35         }
36 }

I tested the code before, although at that point I was using static arrays and wanted to change to a dynamic size. However, even gdb with offers very little help besides the line number. Do I need to individually malloc each student struct, or am I missing something entirely different here?

EDIT: It seems the code works when I allocate memory to each student in the while loop through:

S[i] = (student *)malloc(sizeof(student));

So that seems to have fixed the issue. I'll run some tests to make sure.


Solution

  • On line 19 you are allocating enough space for N student pointers but not allocating space for the student structs them selves. You would need to do something like:

    for( int i = 0; i < N; i++) {
         S[i] = malloc(sizeof(struct __student));
    }