I entered the following long question into bard.google.com . Note also that if you are unsatisfied with the code, you can incrementally tell Bard what to change in the code. But eventually, you will have to copy the resulting code, and discover and fix minor errors by yourself. ==== I want to write code in C to define a substitute malloc, realloc, memalign and free that can find bugs such as double-free. I will keep my own pool of chunks, each of size 32 and aligned on a 32-byte boundary. Then allocate an is_used array of 1M bytes set to '0' (false) or '1' (true) if the chunk is used. Recall that to allocate an aligned array, do something like: int pool_of_chunks[1024*1024*32] __attribute__((aligned(32))); Finally, for any malloc request of size 32 or less, return a pointer to the chunk in the pool_of_chunks that is allocated, and set the corresponding entry in the is_used array to 1. If free is called on the address of one of these chunks, then sset the correponding entry in the is_used array to 0. If the malloc request is for a size larger than 32, then instead, use the mmap syscall to allocate, and the munmap syscall to free it. In this case, you will need to use a separate C++ map to track what mmap segments are in use. The C++ map uses the address of an mmap segment in memory as the key, and the size of the mmap segment as the value, so that later when free() is called, it can later munmap the segment and remove the entry. Initialize all chunks with some pattern like 0b10101010 for each byte. After doing free(), populate the chunk again with 0b10101010 bytes. When doing malloc/memalign/realloc/etc., verify that the chunk still has bytes with 0b10101010, and signal an error if it doesn't. Note that memalign() automatically aligns correctly since each chunk is 32-byte aligned, Any larger memalign() will delegate to the mmap syscall. For realloc, we can create a new buffer of the specified size, copy data from the the old buffer pointed to by ptr, and then free the old buffer. I also wish to add extra code to test for buffer overruns. So, I want to have two adjacent chunks for each chunk allocated. To do this, allocate ony the odd-numbered chunks in the pool_of_chunks array. Then you can just examine all chunks in your pool_of_chunks[] array to verify that all unused chunks have the 0b10101010 pattern. So, the code for all of this should be very simple. And of course, protect your malloc/memalign/free functions with a mutex, since we have multiple threads. And if you are printing, stop using the modified malloc while printing, in case printf calls malloc.