How dmalloc library determines that occurred out of bounds access has occured?

249 Views Asked by At

When this code was executed, the library dmalloc somehow determined that there was an out of bounds memory access. As it allocated 1023 elements and attempted to access 1024th element. (Array index is 0-based).

#include "dmalloc.h"
int main(){

    char *ch = malloc(1023);
    ch[1023] = 0x00;
    return 0;
}

How can it know?

2

There are 2 best solutions below

0
Some programmer dude On

When using the dmalloc library, it actually allocates more than you request. It keeps one area before and one after the memory it returns to you. These areas are filled with special values that are then checked when you free the memory. If those values are not correct, then you clearly have modified memory out of bounds.

0
unwind On

The easiest way is to use sentinels, which are simply blocks of memory that is filled-in with a known pattern by dmalloc. It can then check if that pattern has been destroyed, and flag an error.