小编Joh*_*atz的帖子

c free() 导致崩溃,但数据本身正常工作并且大小正确

每次当我尝试释放结构中的字符串之一时,我的程序都会崩溃,以下是我调用的函数和结构:

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 …
Run Code Online (Sandbox Code Playgroud)

c malloc free memory-management data-structures

2
推荐指数
1
解决办法
125
查看次数

标签 统计

c ×1

data-structures ×1

free ×1

malloc ×1

memory-management ×1