I'm trying to implement a struct which contains strings (char *). I'm a bit lost as I'm able to compile my code but it's crashing without additional information from the OS (most likely a memory issue).
My struct:
typedef struct student
{
int matrikelnummer;
char *name;
struct student *next;
} student;
While trying to properly allocate the memory for *name I'm failing:
void insert_student(student **hash_table)
{
char *name;
int matrikelnummer;
student *temp = malloc(sizeof(student));
if (temp == NULL)
return;
printf("Neuer Student hinzufuegen:\n");
printf("Name: ");
scanf("%s", &name);
temp->name = malloc(strlen(*name) + 1);
if (temp->name == NULL)
return;
strcpy(temp->name, *name);
printf("Matrikelnumer: ");
scanf("%i", temp->matrikelnummer);
temp->next = NULL;
hash_table[get_hash_key(temp->matrikelnummer)] = &temp;
}
The program is crashing right after:
scanf("%s", &name);
I already read through some strcpy/strdup discussions but I thought this should work as implemented.
I'm sure it's a memory issue but I tried more or less all different types of declaring/allocating I'm aware of (doesn't mean too much ;)).
Any help appreciated.
*I know that there is some stuff missing when it comes to proper use of hash tables/linked list. It's just the beginning of a new little project for study purpose.
edit - adding FIXED function - void insert_student(student **hash_table):
void insert_student(student **hash_table)
{
char *name = malloc(100);
student *temp = malloc(sizeof(student));
if (temp == NULL || name == NULL)
return;
printf("Neuer Student hinzufuegen:\n");
printf("Name: ");
scanf("%99s", name);
temp->name = malloc(strlen(name) + 1);
if (temp->name == NULL)
return;
strcpy(temp->name, name);
free(name);
name = NULL;
printf("Matrikelnumer: ");
scanf("%d", &temp->matrikelnummer);
temp->next = NULL;
hash_table[get_hash_key(temp->matrikelnummer)] = &temp;
}
name