malloc对内存对齐有哪些保证? [英] Which guarantees does malloc make about memory alignment?

查看:391
本文介绍了malloc对内存对齐有哪些保证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下代码:

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的倍数.还有其他规则吗?

I want to know how the allocation and padding is done by malloc(). Looking at the output I can see that the starting address is a multiple of 8. Arethere any other rules?

推荐答案

附带此文档页面

在GNU系统中,由malloc或realloc返回的块的地址始终是8的倍数(在64位系统上为16).

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实现是特定于系统的.它们所有人都保留一些内存用于自己的簿记(例如,分配的块的实际长度),以便能够在调用free时正确释放该内存.如果需要与特定边界对齐,请使用其他功能,例如 posix_memalign .

In general, malloc implementations are system-specific. All of them keep some memory for their own bookkeeping (e.g. the actual length of the allocated block) in order to be able to release that memory correctly when you call free. If you need to align to a specific boundary, use other functions, such as posix_memalign.

这篇关于malloc对内存对齐有哪些保证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆