Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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

Code Block
bgColor#ffcccc
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 = realloc(ptr, resize)) == NULL) {
  /* Handle error */
}

...

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
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);

...