Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If free() knows the length of my array, why can't I ask for it in my own code?

I know that it's a common convention to pass the length of dynamically allocated arrays to functions that manipulate them:

void initializeAndFree(int* anArray, size_t length);  int main(){     size_t arrayLength = 0;     scanf("%d", &arrayLength);     int* myArray = (int*)malloc(sizeof(int)*arrayLength);      initializeAndFree(myArray, arrayLength); }  void initializeAndFree(int* anArray, size_t length){     int i = 0;     for (i = 0; i < length; i++) {         anArray[i] = 0;     }     free(anArray); } 

but if there's no way for me to get the length of the allocated memory from a pointer, how does free() "automagically" know what to deallocate when all I'm giving it is the very same pointer? Why can't I get in on the magic, as a C programmer?

Where does free() get its free (har-har) knowledge from?

like image 449
Chris Cooper Avatar asked Apr 16 '10 05:04

Chris Cooper


People also ask

How does free () knows the size of the block to be freed because malloc only returns the starting address?

So the question comes, that how the free() function know about the size of the block to deallocate? When we use the dynamic memory allocation techniques for memory allocations, then this is done in the actual heap section. It creates one word larger than the requested size. This extra word is used to store the size.

Can you free part of an array in C?

You can't free part of an array - you can only free() a pointer that you got from malloc() and when you do that, you'll free all of the allocation you asked for.

What should we do if we dont know the size of an array?

If you will never know the exact size of the array, use vectors (because vectors are the C++ built in function for arrays of unknown size). Well, besides vectors, C++ has other containers, and various libraries have even more of them.

How does malloc know memory to free when a user calls free on a pointer?

When you call malloc() , you specify the amount of memory to allocate. The amount of memory actually used is slightly more than this, and includes extra information that records (at least) how big the block is.


1 Answers

Besides Klatchko's correct point that the standard does not provide for it, real malloc/free implementations often allocate more space then you ask for. E.g. if you ask for 12 bytes it may provide 16 (see A Memory Allocator, which notes that 16 is a common size). So it doesn't need to know you asked for 12 bytes, just that it gave you a 16-byte chunk.

like image 156
Matthew Flaschen Avatar answered Oct 14 '22 00:10

Matthew Flaschen