In C programming, you can pass any kind of pointer you like as an argument to free, how does it know the size of the allocated memory to free? Whenever I pass a pointer to s
This answer is relocated from How does free() know how much memory to deallocate? where I was abrubtly prevented from answering by an apparent duplicate question. This answer then should be relevant to this duplicate:
For the case of malloc
, the heap allocator stores a mapping of the original returned pointer, to relevant details needed for free
ing the memory later. This typically involves storing the size of the memory region in whatever form relevant to the allocator in use, for example raw size, or a node in a binary tree used to track allocations, or a count of memory "units" in use.
free
will not fail if you "rename" the pointer, or duplicate it in any way. It is not however reference counted, and only the first free
will be correct. Additional free
s are "double free" errors.
Attempting to free
any pointer with a value different to those returned by previous malloc
s, and as yet unfreed is an error. It is not possible to partially free memory regions returned from malloc
.