释放内存C

时间:2019-01-21 01:22:09

标签: c memory-management

我在尝试释放结构属性的内存时遇到错误。该代码中的问题出在哪里?

struct Employee {
    char * name;
    int id;
};

struct Employee* new_Employee(char *name, int id) {
    struct Employee* this = (struct Employee*)malloc(sizeof(struct Employee));
    if (this == NULL) {
        return NULL; // Out of memory...
    }
    this->name = name;
    this->id = id;
    return this;
}

int main() {

    // Create an employee
    struct Employee *employee1 = new_Employee("Person A", 1);

    free(employee1 -> name);

}

错误

Homework_0_0(81607,0x10ffba5c0) malloc: *** error for object 0x10a41ffab: pointer being freed was not allocated
Homework_0_0(81607,0x10ffba5c0) malloc: *** set a breakpoint in malloc_error_break to debug

0 个答案:

没有答案