Do not invoke
realloc() to modify the size of allocated objects that have stricter alignment requirements than those guaranteed by
malloc(). Storage allocated by a call to the standard
aligned_alloc() function, for example, can have stricter than normal alignment requirements. The C standard requires only that a pointer returned by
realloc() be suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement.
Noncompliant Code Example
This noncompliant code example returns a pointer to allocated memory that has been aligned to a 4096-byte boundary. If the
resize argument to the
realloc() function is larger than the object referenced by
realloc() will allocate new memory that is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement but may not preserve the stricter alignment of the original object.
When compiled with GCC 4.1.2 and run on the x86_64 Red Hat Linux platform, the following code produces the following output:
ptr1 is no longer aligned to 4096 bytes.
This compliant solution allocates
resize bytes of new memory with the same alignment as the old memory, copies the original memory content, and then frees the old memory. This solution has implementation-defined behavior because it depends on whether extended alignments in excess of
_Alignof (max_align_t) are supported and the contexts in which they are supported. If not supported, the behavior of this compliant solution is undefined.
Compliant Solution (Windows)
Windows defines the
_aligned_malloc() function to allocate memory on a specified alignment boundary. The
_aligned_realloc() [MSDN] can be used to change the size of this memory. This compliant solution demonstrates one such usage:
alignment arguments for
_aligned_malloc() are provided in reverse order of the C Standard
Improper alignment can lead to arbitrary memory locations being accessed and written to.
|Supported, but no explicit checker|
|Axivion Bauhaus Suite|
|LDRA tool suite|
|44 S||Enhanced enforcement|
|CERT_C-MEM36-a||Do not modify the alignment of objects by calling realloc()|
|CERT C: Rule MEM36-C||Checks for alignment change after memory allocation (rule fully covered)|