Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free a pointer without knowing the length [duplicate]

Tags:

c

pointers

free

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.

like image 338
Sait Avatar asked Feb 21 '23 14:02

Sait


1 Answers

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.

like image 65
David Heffernan Avatar answered Mar 05 '23 08:03

David Heffernan