Amazon Interview Question
Developer Program EngineersCountry: India
Interview Type: In-Person
When malloc is called, it stores information about the amount of memory it's going to allocate, adjacently to the memory block, then free simply reads that information.
Thanks Antoni for your respnse.....
Can we(as a programmer) access that structure/information,if yes then how?
malloc() is implementation/compiler dependent, as well as free() so there is no standard way to do it.
Anyway you can write a wrapper for your malloc function and then calculate the information you want. Here's a sample implementation I found on stackoverflow:
// my_malloc.c
#define malloc(sz) my_malloc(sz)
typedef struct {
size_t size;
} Metadata;
void *my_malloc(size_t sz) {
size_t size_with_header = sz + sizeof(Metadata);
void* pointer = malloc(size_with_header);
// cast the header into a Metadata struct
Metadata* header = (Metadata*)pointer;
header->size = sz;
// return the address starting after the header
// since this is what the user needs
return pointer + sizeof(Metadata);
}
Google "How to get memory block length after malloc" for a better explanation.
Thats system programming question.. Anyways.. let me put as
When you call any memory management operation, they are basically exposed using some sort of call mechanism but under the hood there are operation which it won't expose (No needed).
So, considering memory to be an array.. when someone called malloc / calloc for allocation. Those calls goes to that big chuck of array, gets the first address of that chuch which is technically capable of service the space requirement of the caller.
Having said that, it is still under system / compiler or system programmer hand what algo he uses to do that.. like best fit / first fit (mostly)...
But doing so, it attaches the small amount of info in itself in what we call as a header and keep track of it for future call or deallocation..
Coming to 2nd part of question, No we cannot for sure and certain of the header size coz its implementation dependent as I explained.
Hope this helps someone..
C++ way for the delete() to remember how much to be destructed is explained below:
Section 16.14 of the C++ FAQ lite answers this:
There are two popular techniques that do this. Both these techniques are in use by commercial-grade compilers, both have tradeoffs, and neither is perfect. These techniques are:
Source: parashift.com/c%2B%2B-faq-lite/num-elems-in-new-array.html
- R@M3$H.N September 24, 2014