Which guarantees does malloc make about memory ali

2020-06-02 16:48发布

问题:

I came across the following code:

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

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?

回答1:

Accdording to this documentation page,

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).

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.



回答2:

The only standard rule is that the address returned by malloc will be suitably aligned to store any kind of variable. What exactly that means is platform-specific (since alignment requirements vary from platform to platform).



回答3:

For 32 bit Linux system:
When malloc() allocate memory, it allocate memory in multiple of 8 (padding of 8) and allocate extra 8 byte for bookkeeping.

For example:

malloc(10) and malloc (12) will allocate 24 Bytes memory (16 Bytes after padding + 8 Byte for bookkeeping).

malloc() do padding because the addresses returned will be multiples of eight, and thus will be valid for pointers of any type. Bookkeeping 8 bytes is used when we call free function. Bookkeeping bytes stores length of allocated memory.