Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the C function free() not delete values? [duplicate]

I'm learning C programming and writing the basic codes like below.

I've learned that function free() can free memory allocated by calloc() and so on.

But obj->id and obj->name after executing Object_destroy have values in spite of being have executed function free().

Why does this happen? Is freeing memory not equal to deleting values?

#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", obj->id); // => 5
  printf("%s\n", obj->name); // => test

  return(0);
}
like image 722
Tetsutaro Endo Avatar asked Feb 27 '26 08:02

Tetsutaro Endo


2 Answers

Think of malloc and free as signing a contract.

malloc is the promise that the chunk of memory belongs to you and won't be given to someone else. It does not guarantee anything but the size about the memory or initialize it in any way. It doesn't even prevent some other function or process from accessing that memory by address, although such access is bad behavior indeed.

free is you signing the memory back over to the allocator and nothing else. The memory is usually not "deleted" since that is a waste of cycles: the next owner will be responsible for putting in meaningful values regardless. Accessing that memory is the same sort of bad behavior as someone else accessing the memory given to you. You don't know if or when that memory is allocated elsewhere, and it's none of your business once you decide to call free.

like image 138
Mad Physicist Avatar answered Mar 02 '26 15:03

Mad Physicist


It is called dangling pointer problem. After freeing dynamic memory, the pointer still points to that address.So, If you access value of dangling pointer, it is invoked undefined behavior.

If you avoid dangling pointer problem, then use the NULL macro. Like:

 free(obj)
 obj = NULL;
like image 26
msc Avatar answered Mar 02 '26 16:03

msc