I’ve been scratching my head for hours on this. This reads data from a text file into the struct (each line has four strings, and each line represents a new student). I am getting a seg fault on the realloc (near the end). I have a suspicion that I am not understanding how the pointer is interacting with malloc/realloc.
struct student* createInitialStudentArray(FILE *fp) {
char buf[20+1] = {0};
int word = 1, studcount = 1;
struct student* studentArray = malloc(sizeof(struct student));
assert(studentArray != NULL);
while (fscanf(fp, " %20s", buf) != EOF) {
if (word % 4 == 1) {
sscanf(buf, "%4d", &studentArray[studcount].studentID);
word++;
}
else if (word % 4 == 2) {
strcpy(studentArray[studcount].lastName, buf);
word++;
}
else if (word % 4 == 3) {
strcpy(studentArray[studcount].firstName, buf);
word++;
}
else if (word % 4 == 0) {
sscanf(buf, "%10lld", &studentArray[studcount].phoneNumber);
word = 1;
studcount++;
studentArray = realloc(studentArray, studcount * sizeof(struct student));
assert(studentArray != NULL);
}
}
return studentArray;
}
What is causing this seg fault?
Thanks in advance,
Gus
If your array has
studcountelements, thenstudentArray[studcount]is past the end of the array, and writing there is not allowed. The valid elements to access are0tostudcount-1. You should replacestudentArray[studcount]withstudentArray[studcount-1]everywhere to write into the last element.Note that doing it this way will give you a
studcountvalue that is too large by1when the loop is done, because the last element of the array is always empty or incomplete.As mentioned by pmg in the comments, another solution is to initialize
studcountto 0 which will fix both the above issues, but then you need to make sure to allocate room for at leaststudcount+1elements before writing a new one.