John Katz
John Katz

Reputation: 31

c free() causes crash, but the data itself works normally and is the correct size

My program crashes every time when I try to free one of the strings in my struct, here are the functions I call and the struct:

typedef struct course
{
    char *id;
    char *name;
    double credits;
    DynamicArray preCourses;
} *Course;


Course c2;
createCourse("345682", "Cyberpunk and the Future", 3, &c2);
destroyCourse(c2);

Here is the code for the creation function:

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;
}

The free function:

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);
}

The string itself is located in the memory, and is the right length. Thanks for any and all of the help!

Upvotes: 2

Views: 127

Answers (1)

David Ranieri
David Ranieri

Reputation: 41055

Course temp= malloc(sizeof(Course));

Course is typedefed as a pointer, you need to reserve space for the whole struct, not for a pointer to it, change to:

Course temp = malloc(sizeof(struct course));

or better yet

Course temp = malloc(sizeof(*temp));

Upvotes: 5

Related Questions