Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added a Windows compliant solution and called out _aligned_malloc's swapped parameter order.

...

Code Block
bgColor#ccccff
langc
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)

On Windows, aligned allocations happen via calls to _aligned_malloc() and can be realocated with calls to _aligned_realloc()[MSDN].  This compliant solution demonstrates one such usage.

Code Block
bgColor#ccccff
langc
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()

Risk Assessment

Improper alignment can lead to arbitrary memory locations being accessed and written to.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MEM36-C

low

probable

high

P6

L3

 

...