in my C program i'm trying to create an array of structs. For memory allocation im trying to make it dynamic, growing as long as it needs to, unfortunately, everytime it crashes on the realloc.
void readsaveusers(char* filename, User *users) {
FILE *file;
file = fopen(filename, "r");
if (file == NULL) printf("Error reading file\n");
char line[200];
users = malloc(sizeof(struct user *));
for (int i = 0; !feof(file); i ) {
fgets(line, 200, file);
users = realloc(users,sizeof(struct user *) * (i 1));
char *tok = strtok(line, ";");
strcpy(users[i].username, tok);
tok = strtok(NULL, ";");
strcpy(users[i].name, tok);
tok = strtok(NULL, ";");
users[i].gender = tok[0];
tok = strtok(NULL, "/");
users[i].birth_date.day = atoi(tok);
tok = strtok(NULL, "/");
users[i].birth_date.month = atoi(tok);
tok = strtok(NULL, ";");
users[i].birth_date.year = atoi(tok);
tok = strtok(NULL, "/");
users[i].account_creation.day = atoi(tok);
tok = strtok(NULL, "/");
users[i].account_creation.month = atoi(tok);
tok = strtok(NULL, ";");
users[i].account_creation.year = atoi(tok);
tok = strtok(NULL, ";");
strcpy(users[i].pay_method, tok);
tok = strtok(NULL, ";");
strcpy(users[i].account_status, tok);
}
printf("Saved file\n");
fclose(file);
}
CodePudding user response:
This:
users = realloc(users,sizeof(struct user *) * (i 1));
^
|
|
doh!
allocates memory for i 1
pointers to struct user
. Assuming the structure itself is larger than a pointer to it (a reasonable assumption), you will overwrite the allocated memory and bomb.
You meant:
void * const np = realloc(users, (i 1) * sizeof *users);
if (np != NULL)
{
users = np;
}
else
{
fprintf(stderr, "Memory allocation failure, aborting\n");
exit(1);
}
Note use of "new pointer" (np
) variable to check if the allocation succeeds. This could be simplified since the original value is not actually needed when doing an exit()
to handle the error, but I left it as illustration.