NetApp Interview Question
Software Engineer / DevelopersI am not sure about this. Did you mean that the malloc actually allocates few bytes more for the information of the allocated bytes?
I checked out but it seems not..
Somebody correct me.
Unfortunately, there is no standard or portable way. (Some compilers provide nonstandard extensions.) If you need to know, you'll have to keep track of it yourself.ex some compiler have malloc.h header in which _msize()function to get size.
but The malloc function allocates a memory block of at least size bytes. The block may be larger than size bytes because of space required for alignment and maintenance information
so its implementation dependet ...
BUT HOW FREE() KNOWS how much memory to free?
sol-> when we request memory from malloc . compiler writes some info about total size ,checksum etc just before memory allocated for malloc and free uses that information to free memory. it gets ptr and read memory just befor that to get info
how much to free
in the function try to allocate memory untill you exhast all (try allocating like 2, 4, 8, 16, 32, 64, 128 etc), take count for all. when you done this you know how much more memory you newly allocated. freed all memory you allocated. free the memory pointed by p. now again find the existing free memory. take the difference will give you the memory pointed by p. this is kind of not direct method, but careful code gives you the output needed
- allocate all remaining memory and exhast all free memory
- free the memory pointed by 'p' now
- try to allocate the memory now using chunks like 1, 2, 4, 8, 16, 32, 64, 128 etc untill all memory exhast again. once last chunk is not allocted, then try for it half untill you succeeded
- now you know how much memory you allocated which is nothing but your size of memory pointed by 'p'
The memory area just before the starting address that malloc returns contains information about no. of bytes allocated. The similar thing is used by free() to determine the size of the memory to be freed
- Nitin October 02, 2010