...
This noncompliant code example aligns ptr
to a 4096-byte boundary, whereas the realloc()
function aligns the memory to a different alignment.
Code Block | ||||
---|---|---|---|---|
| ||||
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 | ||||
---|---|---|---|---|
| ||||
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); |
...