...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> void func(void) { 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 = realloc(ptr, resize)) == NULL) { /* Handle error */ } } |
The resulting program has undefined behavior because the alignment that realloc()
enforces is different from that of aligned_alloc()
.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> void func(void) { 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); } |
Compliant Solution (Windows)
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <malloc.h> void func(void) { size_t alignment = 1 << 12; int *ptr; int *ptr1; // Original allocation if ((ptr = _aligned_malloc(sizeof(int), alignment)) == NULL) { /* Handle error */ } /* ... */ // Reallocation if ((ptr1 = _aligned_realloc(ptr, 1024, alignment)) == NULL) { _aligned_free(ptr); /* Handle error */ } _aligned_free(ptr1); } |
Note that on Windows, _aligned_malloc()
takes the size and alignment arguments in reverse order from C's _aligned_alloc()
.
...
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MEM36-C | low | probable | high | P6 | L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Bibliography
[ISO/IEC 9899:2011] | Subclause 7.22.3.1, "The aligned_alloc function" |