Thursday, August 1, 2019

c - Free a pointer without knowing the length




I have a sort of theoretical question about freeing a pointer.



I think some guy (the program itself, or OS) have to keep track of the pointers and the length of them. Why?




float* pointer1 = malloc( 100 * sizeof(float) );


For example: I have a float pointer here. Can somebody tell me what is the length of my pointer1 array? There is no way to get the length of that pointer with calling a function/method at run-time right? So how the program (or the OS) is able to free that memory part of the pointer without knowing the real length of it at run-time:



free(pointer1);


If the program knew the length of the pointer to free, why we are not able to get that information and using some other ways to keep track of the lengths. For example:




struct floatArray
{
float* pointer;
int length;
}


So, I am really curious about this issue. I really want to learn how the OS take cares of the pointers lenghts.




Thanks,



Sait.


Answer



The memory manager does indeed maintain metadata about each allocated block of memory. This will likely contain information in addition to the size of the block.



One common way to implement this is to store the metadata in memory just below the memory address which the user program uses to refer to the block. So if the call to malloc returns address p, and the meta data contains n bytes, then the meta data will be stored in addresses p-n to p-1.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...