[cfe-users] Writing an debug memory allocator compatible with -fcatch-undefined-behavior

Thomas Engelmeier tengelmeier at blackberry.com
Fri Feb 7 04:22:33 PST 2014


I try to sanitize an custom allocator (basically it will nuke the contents
on an memory block on free, and therefore needs to prefix an size header).
So far I get an exception when the pointer returned from the allocator  is
casted to any struct and then data assigned.
How can I rewrite the code compliant with -fcatch-undefined-behavior  ?

typedef struct  { int foo, bar; } MyStruct_t;
int main( int argc, char argv[] ) {
    MyStruct_t *p = (MyStruct_t  *) My_MemAlloc( sizeof( MyStruct_t ) );
    p->foo = 0; // crash here
    return 0;
}

Old code:

void *My_MemAlloc(unsigned int size ) {

  unsigned int *rawData;
  MY_ASSERT(size);

  rawData = (unsigned int *) malloc(size + sizeof(unsigned int));
  if( rawData ) {
    rawData[0] = size;
// tried also to keep the void pointer and return rawVoidPtr + sizeof(
unsigned int ) 

    return rawData + 1;
  }
 return NULL;
}



Modified variant:

typedef struct {
 unsigned size;
 char mem[1];
} My_MemoryBlockHeader_t;



void *My_MemAlloc(unsigned int size )
{
 void *rawData;
 void *result = NULL;
 size_t memOffset = offsetof( Tal_MemoryBlockHeader_t, mem );
   
 MY_ASSERT(size);
    
 size_t mySize = size;
 if( (SIZE_MAX - memOffset) < mySize ) {
  return result;
 }
 mySize += memOffset;

 rawData = malloc( mySize );
 if( rawData ) {
   My_MemoryBlockHeader_t *hdr = rawData;
   hdr->size = size;
   result = rawData + memOffset; // or hdr->mem
 }
 return result;
}








More information about the cfe-users mailing list