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; } _______________________________________________ cfe-users mailing list cfe-users@cs.uiuc.edu http://lists.cs.uiuc.edu/mailman/listinfo/cfe-users