https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80023
Bug ID: 80023 Summary: missing diagnostic on aligned_alloc with invalid alignment Product: gcc Version: 7.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: middle-end Assignee: unassigned at gcc dot gnu.org Reporter: msebor at gcc dot gnu.org Target Milestone: --- As is evident from bug 80020, it's easy to get confused about the order of arguments to aligned_alloc, not just for users but also for implementers. Users can accidentally swap the arguments and pass the size where alignment is expected and vice versa. That can lead to allocating less space than required and, ultimately, to a buffer overflow. The C standard, as amended by defect report 460 and N2072 (http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2072.htm), specifies that: If the value of alignment is not a valid alignment supported by the implementation or the value of size is not positive the function shall fail by returning a null pointer. Since only powers of 2 are valid alignments, GCC could help prevent some of the worst consequences of the mistake above by detecting and diagnosing calls to aligned_alloc whose alignment is known not to be valid, similar to how it diagnoses such calls to __builtin_alloca_with_align (a function whose argument order is, ironically, the opposite of aligned_alloc). $ cat z.c && gcc -O2 -S -Wall -Wextra -Wpedantic z.c void f (void*); void g (void) { void *p = __builtin_aligned_alloc (40, 32); f (p); } void h (void) { void *p = __builtin_alloca_with_align (32, 40); f (p); } z.c: In function ‘h’: z.c:11:46: error: second argument to function ‘__builtin_alloca_with_align’ must be a constant integer power of 2 between ‘8’ and ‘2147483648’ bits void *p = __builtin_alloca_with_align (32, 40); ^~