C 语言:在函数中释放结构成员时出错

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


我有一个指向结构的指针,并试图在一个公共函数中释放内存。因此,我按照下面的代码将指向此指针的指针发送到我的销毁函数。

最初我想取消分配结构的 char* 成员,然后是结构本身。
当我尝试释放成员时它给了我 Bus error (core dumped) 但单独释放结构没问题!。
注意:我加了printf,可以看到可以打印里面的字符串。 任何帮助将不胜感激。

   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;
    }

输出

My_firstname
My_lastname
Bus error (core dumped)

您将 malloc 的指针保存在此处

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

你覆盖这里的指针

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

当您尝试释放被覆盖的指针时,您正在尝试释放 malloc 未返回的指针。

您可能想做这样的事情:

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