C++: Undefined behaviour from realloc and the Clang Optimizer
I was wondering around in some system code and found a strange behaviour between two modes in a piece of code, where the code switches from double to triple buffer mode there's a problem, we've already got two buffers of everything we just want to allocate another but the underlying structure for sets of buffers wants to own them all... So the code went from: SetOfBuffers { Buffer* one; Buffer* two; } To: SetOfBuffers { Buffer* one; Buffer* two; Buffer* three; } Creating the third buffer is fine: SetOfBuffers::three = malloc(X); But, the first two is a re-alloc, to reuse the existing buffer: SetOfBuffers::One = realloc(OldSet::one, X); SetOfBuffers::Two = realloc(OldSet::two, X); The problem? I'd start to modify the values in the new set of buffers, the third buffer being used and present. Then the first buffer would be changed present... The second buffer changed present and the information is wrong (I over simplify massively here). Anyway, I was remotely SSH'd