It is not possible to determine how much memory was allocated from just the pointer.
sizeof(p)
is not able to determine at run time the size of the memory block that was previously allocated. sizeof(p)
returns the size of the pointer variable p
, which in turn is calculated at compile time.
p
stores only the starting address of the memory block that has been allocated.
Whenever you allocate a block of memory, malloc()
returns the starting address of that block, but the end of the block can not be determined from it, since there is no terminator type to delimit the end of that block.
You are the one who should know where the end of the block is, so you should store the length of the block somewhere to remember its exact size. p>
On the other hand, you can implement a mechanism capable of retaining the size of the allocated block together with its pointer, for example:
#include <stdlib.h>
#include <stdio.h>
struct pointer_s
{
size_t size;
void * p;
};
typedef struct pointer_s pointer_t;
pointer_t * my_malloc( size_t s )
{
pointer_t * ptr = malloc(sizeof(pointer_t));
ptr->p = malloc(s);
ptr->size = s;
return ptr;
}
void my_free( pointer_t * ptr )
{
free(ptr->p);
free(ptr);
}
int main( void )
{
pointer_t * p = my_malloc( 123 );
printf( "%ld\n", p->size );
my_free( p );
return 0;
}