Versions Compared

Key

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

...

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(0EXIT_FAILURE);
}

ptr[0] = 12;
ptr[1] = 25;

printf("memory aligned to %d bytes\n\n",align);
printf("ptr[0]   : %p = %d\n",ptr, ptr[0]);
printf("ptr[1]   : %p = %d\n\n",&ptr[1], ptr[1]);

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

printf("After realloc(): \n");
printf("ptr1[0]   : %p = %d\n",ptr1, ptr1[0]);
printf("ptr1[1]  : %p = %d\n\n",&ptr1[1], ptr1[1]);

free(ptr1);
return 0;
}

...

Code Block
memory aligned to 4096 bytes

ptr[0]   : 0x1f8af000 = 12
ptr[1]   : 0x1f8af004 = 250x1621b000

After realloc():
ptr1[0]   : 0x1f8ae010 = 12
ptr1[1]  : 0x1f8ae014 = 250x1621a010

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.

...