I need some help to deallocate memory for a struct.
I'm storing a pointer to a memory location in a variable but I want to deallocate the memory after use. However, when I try to deallocate the memory it only deallocates the first structure item (name
) and age
remains in memory. My code can be seen below.
int main(int argc, char **argv)
{
struct employee {
char *name;
int age;
};
// Make pointer, employee struct and put struct in memory at pointer location
struct employee *employee_1;
struct employee new_employee;
new_employee.name = "Sue";
new_employee.age = 26;
employee_1 = (struct employee *) malloc(sizeof(new_employee));
(*employee_1).name = new_employee.name;
(*employee_1).age = new_employee.age;
// ... Some operations done
// Deallocate memory location
free(employee_1);
return 0;
}
Both the name and age of the employee are definitely being stored at the memory location, but I can't deallocate them both. I have tested this to have more than two items in the struct and each time it's only the first item that is deallocated.
I have tried a few different methods like deallocating each individually in case that would work free((*employee_1).name)
but this throws an error. Any help would be appreciated.