C语言 : Error in Freeing members of struct in an a function

标签 c struct malloc structure free


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

最初我想取消分配结构的 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);

关于C语言 : Error in Freeing members of struct in an a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42322943/

相关文章:

c - 在c中打印对象数组

python - 为 Windows 7 编译 IP2Location Python 扩展

c - 正确使用 malloc()

c - 地址未堆叠、分配或(最近)释放

c++ - 使用 openssl 生成 DSA key 对

c - Makefile 抛出重定位错误

c - 如何读取文件并将内容放入结构中(使用 c)?

c - 包装类成员访问

c - 灵活的数组成员是否会增加结构的大小?

c - 简单的链表程序不起作用