我遇到了以下代码:
int main()
{
char *A=(char *)malloc(20);
char *B=(char *)malloc(10);
char *C=(char *)malloc(10);
printf("\n%d",A);
printf("\t%d",B);
printf("\t%d\n",C);
return 0;
}
//output-- 152928264 152928288 152928304
我想知道分配和填充是如何通过malloc()
完成的。查看输出可以看出起始地址是8的倍数,还有其他规则吗?
最佳答案
the address of a block returned by malloc or realloc in the GNU system is always a multiple of eight (or sixteen on 64-bit systems).
通常,malloc
实现是系统特定的。它们都为自己的簿记保留一些内存(例如,分配 block 的实际长度),以便在您调用 free
时能够正确释放该内存。如果您需要对齐到特定边界,请使用其他功能,例如 posix_memalign
.
关于c - malloc 对内存对齐有哪些保证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8575822/