Hello, Im learning C and I'm trying to create a function which returns a pointer to a dynamically allocated struct which stores an array of strings.
The number of strings stored in the depends on the number of lines a file has, so I retrieve them. Nothing wrong so far, but when I try to copy the user's input into the struct I get a segfault.
typedef struct Groceries
{
int done;
int undone;
char* name[32];
} Groceries
Groceries* create_groceries_list()
{
...
int lines = read_lines(f); // each line of this file is a grocery
Groceries* grocery = malloc(sizeof(*grocery) + lines * (sizeof(*grocery->name));
while(!feof(f)) // bad practice
{
....
char g[64];
printf("grocery name (tomatoes, carrots...\n");
scanf("%s", g);
memcpy(groceries->name[lines], g, sizeof(g)); // SEGFAULT
lines++;
....
}
}
I fixed it by dynamically allocating memory for the groceries before copying my buffer into it, but I would like to understand why my code above is wrong (preallocating the amount of memory I need)
any explanation would be appreciated