...
This aligned_alloc()
function was introduced in the C11 standard [ISO/IEC 9899:2011].
Noncompliant Code Example
This noncompliant code example aligns ptr
to a 4096-byte boundary, whereas the realloc()
function aligns the memory to a different alignment.
...
The resulting program has undefined behavior because the alignment that realloc()
enforces is different from that of aligned_alloc()
.
Implementation Details
When compiled with GCC Version 4.1.2 and run on the x86_64 Red Hat Linux platform, the following code produces the following output:
...
Unfortunately, ptr1
is no longer aligned to 4096 bytes.
Compliant Solution
This compliant solution implements an aligned realloc()
function. It allocates resize
bytes of new memory with the same alignment as the old memory and then moves the old memory there, consequently, freeing up the old memory.
Code Block | ||||
---|---|---|---|---|
| ||||
size_t resize = 1024; size_t alignment = 1 << 12; int *ptr; int *ptr1; if ((ptr = aligned_alloc(alignment, sizeof(int))) == NULL) { /* handle error */ } /* ... */ if ((ptr1 = aligned_alloc(alignment, resize)) == NULL) { /* handle error */ } if ((memcpy(ptr1, ptr, sizeof(int)) == NULL) { /* handle error */ } free(ptr); |
Risk Assessment
Improper alignment can lead to arbitrary memory locations being accessed and written to.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC36MEM36-C | highlow | probable | mediumhigh | P12P6 | L1L3 |
Bibliography
[ISO/IEC 9899:2011] Section 7.22.3.1
...