I'm trying to import data from a file but I made a mistake (after this code below) so I was going to make some debugging, adding so the 15th line of this code:
fscanf(input, "%d %d", & numofusers, & numofmovies);
//-----users list allocation
for (int i = 0; i < numofusers; i ) {
curruser -> usercode = i 1;
//without this 7th line I get a segmentation fault at line 15 (without line 15 program termines successfully)
printf("%d %d %d\n\n", numofusers, numofmovies, curruser -> usercode);
//through this line of code I understood that it does what I want it to do
curruser -> next = calloc(1, sizeof(struct user * ));
curruser = curruser -> next;
}
curruser = headuser;
//--------
printf("!%d!\n", numofmovies);
The first line of the file contains two integers, which are read with no issues, then I try to allocate some memory for the users.
If the first printf
is there, no segmentation fault and everything works; otherwise it doesn't. I've already tried some potential solutions from this website but they didn't fix the issue. There must be somewhere I'm not aware of...
CodePudding user response:
You're allocating the wrong amount of memory:
calloc(1, sizeof(struct user * ));
You are allocating enough memory for a pointer, not a whole object.
It should be
calloc(1, sizeof(struct user));
(And, there's no reason to use calloc
here over malloc
.)