Joh*_*atz 2 c malloc free memory-management data-structures
每次当我尝试释放结构中的字符串之一时,我的程序都会崩溃,以下是我调用的函数和结构:
typedef struct course
{
char *id;
char *name;
double credits;
DynamicArray preCourses;
} *Course;
Course c2;
createCourse("345682", "Cyberpunk and the Future", 3, &c2);
destroyCourse(c2);
Run Code Online (Sandbox Code Playgroud)
下面是创建函数的代码:
CourseResult createCourse(char *id, char *name, double credits, Course *course)
{
assert(name != NULL || id != NULL);
Course temp= malloc(sizeof(Course));
if(temp == NULL)
return COURSE_ILLEGAL_PARAMETER;
temp->id = (char *)malloc((strlen(id)+1));
if (temp->id == NULL) {
free(temp);
return COURSE_MEMORY_ERROR;
}
temp->name = (char *)malloc((strlen(name)+1));
if (temp->name == NULL) {
free(temp->id);
free(temp);
return COURSE_MEMORY_ERROR;
}
temp->preCourses=createDynamicArray();
if(temp->preCourses == NULL){
free(temp->name);
free(temp->id);
free(temp);
return COURSE_MEMORY_ERROR;
}
strcpy(temp->id,id);
strcpy(temp->name,name);
temp->credits=credits;
*course = temp;
return COURSE_OK;
}
Run Code Online (Sandbox Code Playgroud)
免费功能:
void destroyCourse(Course course1)
{
destroyDynamicArray(course1->preCourses);
printf("%s", course1->id); //prints 345682
printf("%d", strlen(course1->id)); //prints 6
free(course1->id); //crashes here
free(course1->name);
free(course1);
}
Run Code Online (Sandbox Code Playgroud)
字符串本身位于内存中,并且长度正确。感谢您的任何和所有帮助!
Course temp= malloc(sizeof(Course));
Run Code Online (Sandbox Code Playgroud)
Coursetypedefed 为指针,您需要为整个 保留空间struct,而不是为指向它的指针,更改为:
Course temp = malloc(sizeof(struct course));
Run Code Online (Sandbox Code Playgroud)
或者更好
Course temp = malloc(sizeof(*temp));
Run Code Online (Sandbox Code Playgroud)