开发者

c free() function question [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

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

Hi,

when i have following code:

void *ptr = malloc(100); // alloc开发者_C百科 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


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.


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜