Search code examples
clinuxmemorymallocglibc

How to modify the malloc behavior in glibc and test if it works as expected?


I want to use malloc to allocate memory, but I don't want to use a dynamic allocation way in malloc. Instead, I want to use malloc to allocate a large block/pool so that I can "new" some variables/objects into this large memory block/pool. Therefore, I would like to modify the malloc source code (e.g., malloc/malloc.c) in glibc to make it work for my scenario.

What is the most convenient and efficient way to modify glibc source codes and also test its functionality? One way that comes to my mind is to download the glibc source, modify the code, and then configure/make/make install, but it would be very cumbersome because I have to test my modified version of malloc frequently to make sure it works properly.

Thank you so much for your kind help! All the answers and thoughts are appreciated.


Solution

  • You can use LD_PRELOAD with your code (assuming it is dynamically linked) to insert your own malloc implementation.

    What you want sounds a lot like Arena Allocation. This library might already do what you need: https://github.com/thejefflarson/arena