stratagus icon indicating copy to clipboard operation
stratagus copied to clipboard

Undefined behaviour due to alignment issue

Open Ace17 opened this issue 3 years ago • 0 comments

/tmp/dev/stratagus/src/network/net_message.cpp:62:38: runtime error: store to misaligned address 0x60300012d3fb for type 'uint16_t', which requires 2 byte alignment
0x60300012d3fb: note: pointer points here
 00  00 0b 05 be be be be be  be be be be be be be be  00 00 00 00 00 00 00 00  02 11 00 00 18 00 00

While this could work in practice, an optimizing compiler is free to consider that buf will always be aligned to 2 bytes, and to optimize the code accordingly (Moreover, this will cause issues on architectures that are less forgiving that x86). Here, buf isn't aligned to 2 bytes, so we're invoking undefined behaviour.

size_t serialize16(unsigned char *buf, uint16_t data)
{
	if (buf) {
		*reinterpret_cast<uint16_t *>(buf) = htons(data);
	}
	return sizeof(data);
}

Here's a way this function could be written without invoking UB :

	if (buf) {
                uint16_t val = htons(data);
		memcpy(buf, &val, sizeof val);
	}

( It's very likely that the call to memcpy will be optimized away )

Ace17 avatar Jul 05 '22 07:07 Ace17