我有一个指向结构的指针,并试图在一个公共(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/