Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Minor edits; reviewed.

...

This noncompliant code example aligns ptr to a 4096-byte boundary, whereas the realloc() function aligns the memory to a different alignmentsuitable, but likely different, alignment:

Code Block
bgColor#ffcccc
langc
#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  when the alignment that realloc() enforces is different from that of aligned_alloc().

...

Code Block
memory aligned to 4096 bytes
ptr = 0x1621b000

After realloc():
ptr1 = 0x1621a010

Unfortunately, ptr1 is no longer aligned to 4096 bytes.

...

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 then frees the old memory:

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

...

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

Risk Assessment

...