c free() 导致崩溃,但数据本身正常工作并且大小正确
c free() causes crash, but the data itself works normally and is the correct size
每次我尝试释放结构中的一个字符串时,我的程序都会崩溃,以下是我调用的函数和结构:
typedef struct course
{
char *id;
char *name;
double credits;
DynamicArray preCourses;
} *Course;
Course c2;
createCourse("345682", "Cyberpunk and the Future", 3, &c2);
destroyCourse(c2);
创建函数的代码如下:
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;
}
免费功能:
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);
}
字符串本身位于内存中,并且是正确的长度。
感谢您提供的所有帮助!
Course temp= malloc(sizeof(Course));
Course
被typedefed为指针,你需要为整个struct
保留space,而不是指向它的指针,改为:
Course temp = malloc(sizeof(struct course));
或更好
Course temp = malloc(sizeof(*temp));
每次我尝试释放结构中的一个字符串时,我的程序都会崩溃,以下是我调用的函数和结构:
typedef struct course
{
char *id;
char *name;
double credits;
DynamicArray preCourses;
} *Course;
Course c2;
createCourse("345682", "Cyberpunk and the Future", 3, &c2);
destroyCourse(c2);
创建函数的代码如下:
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;
}
免费功能:
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);
}
字符串本身位于内存中,并且是正确的长度。 感谢您提供的所有帮助!
Course temp= malloc(sizeof(Course));
Course
被typedefed为指针,你需要为整个struct
保留space,而不是指向它的指针,改为:
Course temp = malloc(sizeof(struct course));
或更好
Course temp = malloc(sizeof(*temp));