Question about free () in C language

Possible duplicate:
How do free and malloc work in C?

How to find out for free how many bytes of memory will be available when called in the program?

+4
source share
5 answers

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

That is why you should always call free only the pointer that was returned by malloc .

+8
source

This is done automatically. The corresponding "malloc" has kept the size in a secret place (usually stored with a negative offset from the pointer).

This, of course, means that you can only free memory that matches the block previously allocated by "malloc".

+3
source

The question of how he knows β€œhow many bytes for free” is an error. It's not like each byte individually has a free / unoccupied status bit attached to it (well, maybe, but it will be a terrible implementation). In many implementations, the number of bytes in the distribution may be completely inappropriate; these are data structures used to manage it that are relevant.

+2
source

This is an implementation detail that can and can vary between different platforms. Here is one example of how this can be implemented.

Each call to free must be paired with a call to malloc / realloc , which knows the size request. The malloc implementation may choose to keep this size with the offset of the returned memory. Say, allocating a larger buffer than the requested one, gaining size in front, and then returning the offset to the allocated memory. Then, the free function could simply use the offset of the provided pointer to detect the free size.

for instance

 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 ... } 
+1
source

The answer is implementation specific.

  • malloc can support matching dictionary addresses with data records
  • malloc can allocate a slightly larger block than the requested one and store metadata before or after it actually returns.
  • In some special cases, not intended for general use, free() does not fully work, and in fact it does not track.
0
source

Source: https://habr.com/ru/post/1341349/


All Articles