Although "malloc" and "free" are described in terms of creating allocations and destroying them, their actual role is the reverse of that. The "malloc()" function takes some memory from a pool and indicates that the memory manager is not allowed to use any of the bytes within the allocated range (though bytes that were outside that range, including those immediately preceding and following the allocation, remain available to it). The "free()" function adds memory back to the pool, making it available for future use.
In some allocation systems, the function that releases memory accepts an argument indicating how much memory is being released; others may require that each pool only be used to dispense fixed-size objects. Some of the systems that do such things would allow code to add any chunk of memory that a program won't need for any other purpose to a pool by simply "releasing" it, the memory manager knowing or caring whether the memory came from the pool in the first case. Indeed, in some such systems that may be how the pools get created in the first place: initialize a descriptor for an empty memory pool, and then "release" chunks of storage into it as convenient.
Such an approach to adding storage to a memory pool can't work in C, however, since the only way "free" can know how much memory to add to the pool is to make use of information that was stored somewhere by "malloc". Generally, the information is stored in the space immediately prior to the storage malloc() gives the application. If a pointer wasn't produced by malloc()
, the storage immediately preceding the storage described by the pointer won't contain the information malloc() needs, but will more likely contain a pattern of bytes that looks like it was created by an allocation of some meaningless size. This would have the effect of inviting the memory manager to do whatever it likes with a large chunk of storage that will likely extend beyond the boundaries of the object whose address was passed to it. Hilarity is likely to ensue when the memory manager takes the application up on that invitation.
free()
isn't required to detect any error. Some implementations detect some kinds of errors, but your code shouldn't rely on this. – Birthroot