Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: tweaked a little bit

...

Code Block
bgColor#ffcccc
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 */
}

...

Code Block
#include <stdlib.h>
#include <stdio.h>

int main(void) {
  size_t  size = 16;
  size_t resize = 1024;
  size_t align = 1 << 12;
  int *ptr;
  int *ptr1;

  if (posix_memalign((void **)&ptr, align , size) != 0) {
    exit(EXIT_FAILURE);
  }

  printf("memory aligned to %d bytes\n", align);
  printf("ptr = %p\n\n", ptr);

  if ((ptr1 = realloc((int *)ptr, resize)) == NULL) {
    exit(EXIT_FAILURE);
  }

printf  puts("After realloc(): \n");
  printf("ptr1 = %p\n", ptr1);

  free(ptr1);
  return 0;
}

produces the following (unexpected) output.:

Code Block
memory aligned to 4096 bytes
ptr = 0x1621b000

After realloc():
ptr1 = 0x1621a010

Unfortunately, ptr1 is no longer aligned to 4096 bytes.

Compliant Solution

This compliant solution implements an aligned realloc() function. It allocates new memory of resize bytes with an alignment equal to that of old memory and copies old memory into it. It then frees the old memory.

Code Block
bgColor#ccccff
size_t resize = 1024;
size_t alignment = 1 << 12;
size_t newsize;
int *ptr;
int *ptr1;

if ((ptr = aligned_alloc(alignment , sizeof(int))) == NULL) {
  /* handle error */
}

/* ... */

if ((ptr1 = aligned_alloc(alignment , resize)) == NULL) {
  /* handle error */
}

newsize = MIN(size, resize);
if((memcpy(ptr1, ptr, newsizesizeof(int)) == NULL) {
  /* handle error */
}

free(ptr);

...