I was trying to understand how aligned malloc can be written referencing below post,
How to allocate aligned memory only using the standard library?
There are approaches which basically do this for 16 byte alignment, the memory which is returned is calculated using below,
((uintptr_t)mem+16-1) & ~ (uintptr_t)0x0F;
I am not getting that accepted answer is using 1024 byte memory allocation as it will be 16 byte aligned already. Is this understanding correct?
Shouldn't memory unaligned value be 1026 or 1029 byte which need to be made a multiple of 16 basically?
What about below example code,
#include <stdio.h>
#include <stdlib.h>
void myalignmalloc(size_t size, int align)
{
size_t ext = size % align;
size_t alignsize = size - ext + align; // memory divisible by align value
printf("size: %ld alignsize: %ld\n", size, alignsize);
// TODO: Add code use alignsize to allocate extra memory with alignment
}
//TODO: Add myfree function
int main(void)
{
myalignmalloc(1031, 16);
myalignmalloc(1031, 32);
myalignmalloc(1061, 16);
myalignmalloc(1061, 32);
return 0;
}
//output
//size: 1031 alignsize: 1040
//size: 1031 alignsize: 1056
//size: 1061 alignsize: 1072
//size: 1061 alignsize: 1088
Is this not giving us correct memory size aligned by alignment by just making memory to be multiple of alignment?