开发者

question on free() in C language [duplicate]

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

Po开发者_开发百科ssible Duplicate:

How do free and malloc work in C?

How does free know how many bytes of memory to be free'd when called in a program?


This is implementation specific, but when malloc is called, the size of the allocated memory is kept somewhere (usually offset from the pointer itself). When free is called, it will use that stored size.

This is exactly why you should only ever call free on a pointer that was returned by malloc.


It's done automatically. The corresponding "malloc" has saved the size in a secret place (typically stored at a negative offset from the pointer).

This, of course, mean that you can only free memory that corresponds to a block previously allocated by "malloc".


Asking how it knows "how many bytes to free" is a mistake. It's not like each byte individually has a free/not-free status bit attached to it (well, it could, but this would be an awful implementation). In many implementations the number of bytes in an allocation may be completely irrelevant; it's the data structures used to manage it that are relevant.


It's an implementation detail than can and will vary between different platforms. Here's one example though of how it could be implemented.

Every free call must be paired with a malloc / realloc call which knows the size request. The implementation of malloc could choose to store this size at an offset of the returned memory. Say by allocating a larger buffer than requested, stuffing the size in the front and then returning an offset into the allocated memory. The free function could then simply use the offset of the provided pointer to discover the size to free.

For example

void* malloc(size_t size) {
  size_t actualSize = size + sizeof(size_t);
  void* buffer = _internal_allocate(actualSize);
  *((size_t*)buffer) = size;
  return ((size_t*)buffer) + 1;
}

void free(void* buffer) {
  size_t* other = buffer;
  other--;
  size_t originalSize = *other; 
  // Rest of free
  ...
}


The answer is implementation-specific.

  • malloc might keep a dictionary mapping addresses to data records
  • malloc might allocate a slightly larger block than requested and store metadata before or after the block it actually returns.
  • In some special cases, not intended for general use, free() is completely a no-op and it doesn't actually keep track.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜