Rand0m
Rand0m

Reputation: 372

C Language: Error in Freeing members of struct in an a function


I have a a pointer to a struct, and trying to free the memory in a common function. So I am sending a pointer to this pointer to my destroy function as per the code below.

Initially I want to de-allocate the char* members of the stuct and then the structure itself.
It is giving me Bus error (core dumped) when I try to free the members but it is OK with freeing structure alone!.
Note: I added printf and I can see that I can print the string inside. Any help will be appreciated.

   const size_t name_size = 50;
   typedef struct Student{
        int id;
        char * firstname;
        char * surname;
    } Student; 


    Student* createStudent(void);
    void destroyStudent(Student**);

    int main(){
        Student * student = createStudent();
        student->firstname = "My_firstname";
        student->surname = "My_lastname";
        student->id = 2;
        destroyStudent(&student);
    }

    Student* createStudent(){
        Student * studentPtr = (Student *)malloc(sizeof(Student));
        studentPtr->firstname = (char *) malloc(name_size);
        studentPtr->surname = (char *) malloc(name_size);
        return studentPtr;
    }

    void destroyStudent(Student** ptr){
        printf("%s\n", (*ptr)->firstname);
        printf("%s\n", (*ptr)->surname);
        free((*ptr)->firstname);
        free((*ptr)->surname);
        free(*ptr);
        *ptr = NULL;
    }

Output

My_firstname
My_lastname
Bus error (core dumped)

Upvotes: 2

Views: 809

Answers (1)

user3657941
user3657941

Reputation:

You save the pointers from malloc here

    studentPtr->firstname = (char *) malloc(name_size);
    studentPtr->surname = (char *) malloc(name_size);

You overwrite the pointers here

    student->firstname = "My_firstname";
    student->surname = "My_lastname";

When you try to free the overwritten pointers, you are trying to free pointers that were not returned by malloc.

You probably wanted to do something like this:

    strncpy(student->firstname, "My_firstname", name_size);
    strncpy(student->surname, "My_lastname", name_size);

Upvotes: 1

Related Questions