c - How to find how much space is allocated by a call to malloc()? -


i'm trying write size function this:

size(void *p,int size); 

which return size of array pointed p. example:

int *a = malloc((sizeof(int)*100)); size(a,sizeof(int)); // should return 100 

i think possible because if recall, malloc keeps track of space allocated in header bytes.

here's have far:

int size(void *p, int size) {   p = (unsigned int *)p - 1;   unsigned int elements = (*(unsigned int *)p);   return elements/size; } 

now, assuming size of space allocated in 4 bytes before pointer, should return bytes, or offset. i'm bit in dark. can't figure out specifics of how malloc formats these header bytes. how malloc pack header bits?

thanks, appreciate this. i'm sure there things wrong code , it's not particularly portable , may system dependent, i'm doing fun.

if peek , poke around beyond memory malloc() returns recommend obtaining source code of allocator. faster , safer experimenting. ;-)


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -