I recently learned that dereferencing a pointer not aligned for a certain object (uint32_t* foo = (uint32_t*)7; *foo = 5;
) is in fact undefined behaviour:
C11 section 6.2.8: Alignment of objects:
Complete object types have alignment requirements which place
restrictions on the addresses at which objects of that type may be
allocated. An alignment is an implementation-defined integer value
representing the number of bytes between successive addresses at which
a given object can be allocated. An object type imposes an alignment
requirement on every object of that type: stricter alignment can be
requested using the _Alignas keyword.
Ok, very interesting. But malloc does not seem to care at all about alignment:
7.22.3.4 The malloc function
Synopsis
#include <stdlib.h> void *malloc(size_t size); Description
The malloc function allocates space for an object whose size is
specified by size and whose value is indeterminate. ReturnsThe malloc function returns either a null pointer or a pointer to the
allocated space.
Therefore: is there not a very real chance that doing something like
uint32_t* a = malloc(10*sizeof(uint32_t)); *a = 7;
Invokes undefined behaviour? We have no guarantee that the return value of malloc is aligned to anything, after all.