Recently I was asked a question to implement a very simple malloc
with the following restrictions and initial conditions.
#define HEAP_SIZE 2048
int main()
{
privateHeap = malloc(HEAP_SIZE + 256); //extra 256 bytes for heap metadata
void* ptr = mymalloc( size_t(750) );
myfree( ptr );
return 0;
}
I need to implement mymalloc
and myfree
here using the exact space provided. 256 bytes is nicely mapping to 2048 bits, and I can have a bit array storing if a byte is allocated or if it is free. But when I make a myfree
call with ptr
, I cannot tell how much size was allocated to begin with. I cannot use any extra bits.
I don't seem to think there is a way around this, but I've been reiterated that it can be done. Any suggestions ?
EDIT 1:
- Alignment restrictions don't exist. I assumed I am not going to align anything.
- There was a demo program that did a series of
malloc
s and frees to test this, and it didn't have any memory blocks that were small. But that doesn't guarantee anything.
EDIT 2:
The guidelines from the documentation: Certain Guidelines on your code:
- Manage the heap metadata in the private heap; do not create extra linked lists outside of the provided private heap;
- Design
mymalloc
,myrealloc
,myFree
to work for all possible inputs. myrealloc
should do the following like therealloc
in C++ library:void* myrealloc( void* C, size_t newSize )
:- If
newSize
is bigger than the size of chunk inreallocThis
:- It should first try to allocate a chunk of size
newSize
in place so that new chunk's base pointer also isreallocThis
; - If there is no free space available to do in place allocation, it should allocate a chunk of requested size in a different region; and then it should copy the contents from the previous chunk.
- If the function failed to allocate the requested block of memory, a
NULL
pointer is returned, and the memory block pointed to by argumentreallocThis
is left unchanged.
- It should first try to allocate a chunk of size
- If
newSize
is smaller,realloc
should shrink the size of the chunk and should always succeed. - If
newSize
is 0, it should work like free. - If
reallocThis
is NULL, it should work likemalloc
. - If
reallocThis
is pointer that was already freed, then it should fail gracefully by returning NULL
- If
myFree
should not crash when it is passed a pointer that has already been freed.
int main()
, notvoid main()
. – GingerPlusPlus