CodeSOD: Feeling Free

This post was originally published on this site

The Daily WTF

Jason started work on a C++ application doing quantitative work. The nature of the program involves allocating all sorts of blocks of memory, doing loads of complicated math, and then freeing them. Which means, there’s code which looks like this:

for( i = 0; i < 6; i++ ) { if( h->quant4_bias[i] ) free( h->quant4_bias[i] ); }

This isn’t terribly unusual code. I have quibbles- why the magic number 6, I’d prefer the comparison against nullptr to be explicit- but this isn’t the kind of code that’s going to leave anybody scratching their head. If h->quant4_bias[i] is pointing to actual memory, free it.

But this is how that array is declared:

uint16_t (*quant4_bias[4])[16];

Uh… the array has 4 elements in it. We free six elements. And shockingly, this doesn’t crash. Why not? Well… it’s because we get lucky. Here’s that array declaration with a bit more context:

uint16_t

To read the full article click on the 'post' link at the top.