Custom implementation of malloc in C++

I came across an interview question where they asked to implement malloc() and free function in C++ .

At the very beginning a char array of size 50000 is declared(50000 bytes). Assuming this is the heap memory, write malloc and free functions to allocate blocks of memory and free up memory.

Any one can provide me with C++ working/pseudo code or just explain the mechanism? (obviously code would make it a lot easier to understand).

Thanks, Rohit


While writing a production-level dynamic memory allocator is a very hard task, writing a toy one is straightforward. The question is obviously meant to test your skills, but it is still fair to look for inspiration in the works of others.

"The C Programming Language" by Kernighan & Ritchie contains a simple implementation of malloc . Study it and consider the implications of its design and implementation. Consider how you would improve it to perform better, fragment less, or handle multiple threads. After that, it should no longer be hard to write your own toy allocator, and answer any questions that arise.


There are several different algorithms which can be used. For such a small memory, I'd just prefix each block with a pointer to the next block, and a flag indicating whether it is allocated or freed. An allocation consists of finding a large enough free block, splitting it if necessary, and marking the returned block as allocated. A free consists of marking the block as free. At some point, you also have to coalesce blocks: if two free blocks follow each other, they are merged into one. (I did this during allocation in my implementation.)

The above algorithm isn't very difficult in itself. The real trick is getting all of the different casts and such right. It's a good exercise in very low level programming.


我之前没有测试过它,但我认为可以通过使用新的关键字和模板来支持通用状态来创建所需类型的数组,但我会按照这个问题来找出C ++英雄的响应。

链接地址: http://www.djcxy.com/p/80436.html

上一篇: Malloc vs自定义分配器:Malloc有很多开销。 为什么?

下一篇: 在C ++中定制实现malloc