C - 如何使用 free() 释放内存中的结构?

C - How to use free() to free a struct in memory?

我需要一些帮助来为结构释放内存。

我正在将指向内存位置的指针存储在变量中,但我想在使用后释放内存。但是,当我尝试解除分配内存时,它只会解除分配第一个结构项 (name) 并且 age 保留在内存中。我的代码可以在下面看到。

int main(int argc, char **argv)
{
  struct employee {
    char *name;
    int age;
  };

  // Make pointer, employee struct and put struct in memory at pointer location
  struct employee *employee_1;
  struct employee new_employee;
  new_employee.name = "Sue";
  new_employee.age = 26;
  employee_1 = (struct employee *) malloc(sizeof(new_employee));
  (*employee_1).name = new_employee.name;
  (*employee_1).age = new_employee.age;

  // ... Some operations done
  // Deallocate memory location
  free(employee_1);
  return 0;
}

员工的姓名和年龄肯定都存储在内存位置,但我无法将它们都释放。我已经测试过它在结构中有两个以上的项目,每次它只是第一个被释放的项目。

我已经尝试了几种不同的方法,例如单独解除分配以防万一 free((*employee_1).name) 但这会引发错误。任何帮助将不胜感激。

不,您自己不会 解除分配 age。那不是 "pointer returned by malloc() and family",所以您不需要(调用)free()

引用 C11,章节 §7.22.3.3,(强调我的

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

另外,FWIW,free()接受一个指针,所以即使传递age成员变量的地址也是错误的。一旦程序终止,分配的内存将由 OS 或内存管理器自动释放。

总而言之,您应该仅使用内存管理函数(即 malloc() 和家族)返回的指针调用 free(),仅此而已。其他指针,即使它们是指针,如果不是通过内存管理函数分配内存,(即,snot 是否存储 malloc() 和 family 返回的指针)不需要是 free()-d.

例如,在您的情况下,您不在 (*employee_1).name 上调用 free()(而是使用 employee_1->name,以提供更好的可读性,恕我直言),因为指针未返回通过内存管理功能。这样做会调用 undefined behavior.

也就是说,please see this discussion on why not to cast the return value of malloc() and family in C.