Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c free() function question [duplicate]

Possible Duplicate:
C programming : How does free know how much to free?

Hi,

when i have following code:

void *ptr = malloc(100); // alloc 100 bytes
// do sth
free(ptr);

how does the free() function know how much space has to be freed?

thank you!

--

ok i have found other questions asking the same, please close - sorry

like image 928
Weidling C Avatar asked Mar 12 '26 14:03

Weidling C


2 Answers

This information is usually contained in some memory area managed by the malloc implementation. The information often preceeds the actual memory handed out to you by malloc, but that's an implementation detail, and you cannot rely on anything here.

like image 108
Dirk Avatar answered Mar 14 '26 04:03

Dirk


It's implementation dependent but usually the underlying system mas a map of addresses to blocks and it knows the size from that memory map.

Here is the striped down code from glibc which shows it doing basically what what I just said.

void fREe(Void_t* mem)
{
  arena *ar_ptr;
  mchunkptr p;
  if (__free_hook != NULL) {
    (*__free_hook)(mem, NULL);
  }

  if (mem == 0)                              /* free(0) has no effect */
    return;

  p = mem2chunk(mem);

  if (chunk_is_mmapped(p))                       /* release mmapped memory. */
  {
    munmap_chunk(p);
    return;
  }

  ar_ptr = arena_for_ptr(p);
  chunk_free(ar_ptr, p);
  (void)mutex_unlock(&ar_ptr->mutex);
}
like image 34
Andrew White Avatar answered Mar 14 '26 04:03

Andrew White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!