小编Tet*_*ndo的帖子

为什么 C 函数 free() 不删除值?

我正在学习 C 编程并编写如下基本代码。

我了解到该函数可以释放由等等free()分配的内存。calloc()

但是obj->idobj->name在执行 Object_destroy 后,尽管已执行函数,但仍具有值free()

为什么会出现这种情况?释放内存不等于删除值吗?

#include <stdio.h>
#include <stdlib.h>

typedef struct Object* Object;
struct Object
{
  int id;
  char* name;
};

Object Object_new(int id, char* name)
{
  Object obj = calloc(1, sizeof(struct Object));
  obj->id = id;
  obj->name = name;
  return obj;
}

void Object_destroy(Object obj)
{
  free(obj);
}

int main()
{
  Object obj = Object_new(5, "test");

  printf("%d\n", obj->id); // => 5
  printf("%s\n", obj->name); // => test

  Object_destroy(obj);
  printf("%d\n", …
Run Code Online (Sandbox Code Playgroud)

c malloc free memory-management

3
推荐指数
1
解决办法
1695
查看次数

标签 统计

c ×1

free ×1

malloc ×1

memory-management ×1