Say that you allocate some memory on the heap through malloc
:
someType x = malloc(someSize);
When you don't need x
anymore, you free
it:
free(x)
To perform this operation, I guess, the compiler must know the size of the memory x
points to. I think free
performs something like:
- Read the value contained in
x
(say it is 16). - Determine in some way the memory size allocated at 16 (say it's 8).
- Tell OS that the 16-23 memory region is not longer needed and the OS can do whatever it wants with it.
If the above is true, why the standard doesn't prescribe a function that just performs the above till step 2 and returns the size to the programmer, without actually freeing the memory?
Some (not much convincing) reasons I read online:
malloc()
implementations usually keep track of a region's size, but they may do this indirectly, or round it up to some value, or not keep it at all. It's that true? Can possiblymalloc
not keep track of the size?- Because C is a low-level programming language, it expects you to take care of these issues yourself, but this adds greater flexibility in exactly how you implement it. Ok, this is more philosophical. Nonetheless, C standard has evolved and has provided, over time, more headers, functions and tools.
- You should rewrite every compiler to implement such function. Is that true? If
free
is already implemented, you just need a part of it; the implementation should be trivial.
So, there is a cogent, impellent, real reason why this function is not provided? Or, more likely, why the above reasons are actually important and what I am missing?
I think that this question has been already asked (and very likely a dupe), but I was able only to find similar subjects, for instance (btw the below questions are where I found some of the objections I reported above):
Here is discussed whether such function exists, but not why it doesn't.
Here is discussed about (stack-allocated)arrays.
free
you don't say:free this size
; you just provide the pointer. So the compiler must know how much memory is allocated. Am I wrong?c
standard library which implements themalloc
andfree
functions and that's completely independent by the compiler itself.malloc
. Exposing it won't do you much good.