In an approach to detect the heap corruption I am trying to implement a hash table to keep some information about the malloced memory. This is being done inside glibc itself. When we malloc(), we put the information like address and size in the hash table and when we free(), we deallocate the corresponding hash table entry, again in glibc’s free() itself.
To allocate memory for the hash table i have mmap’d some memory (refrained from using malloc for this, as the chances of process induced heap corruption can corrupt my hash table also).
The issue is that there is no limit to the number of mallocs that a process can ask for, this requires my hash table to be extensible. Since my hash table works on array indices, memory used for hash table need to be contiguous so that using an index we can easily reach the bucket or record. Now, when hash table uses all the memory, i need to do a ‘mmap’ again in such a way that this memory starts where the previous ended. man page of mmap says that we can provide an address to mmap, that will act as a hint to kernel to map virtual memory at that address. To the hash table, it will look like a contguouis chunk of memory. I would like to ask for you suggestions how reliable is this approach and what are the potential pitfalls using this.
If this is Linux, you can use
mremap.If you write your hash table to be based on offsets and not absolute pointers, you can pass the
MREMAP_MAYMOVEflag and never have to worry about allocation failures. (Well, until you exhaust your virtual memory, anyway.)