大家好,最近针对对齐部分想进一步了解
在stackoverflow上看到这个问题
The memset_16aligned function requires a 16-byte aligned pointer passed to it,
or it will crash.
a) How would you allocate 1024 bytes of memory, and align it to a 16 byte
boundary?
b) Free the memory after the memset_16aligned has executed.
Ans:
{
void *mem = malloc(1024+15);
void *ptr = ((uintptr_t)mem+15) & ~ (uintptr_t)0x0F;
memset_16aligned(ptr, 0, 1024);
free(mem);
}
==============================
题目有人讲意思讲的不精确,应该讲塞的下1024B且对移16Byte~
我这边想问两个问题请教
(1) 为何malloc(1024"+15")? 看网站上是说要确定size足够
但是1024本身不是已经是足够的吗?
(2) ((uintptr_t)mem+15) & ~ (uintptr_t)0x0F;
这部分我有看到wiki也是这样列公式,但是自己待一些16进位位置还是感觉不大
我自己第一个想法是mem+16 & ~.... , 虽然也是可行
但大家说15就足够,这部分是为什么呢?
以上请大家指教 3Q