Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which guarantees does malloc make about memory alignment?

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?

like image 759
Amol Sharma Avatar asked Dec 20 '11 12:12

Amol Sharma


People also ask

Is malloc 16 byte aligned?

The GNU documentation states that malloc is aligned to 16 byte multiples on 64 bit systems.

What is the purpose of memory alignment?

The CPU can operate on an aligned word of memory atomically, meaning that no other instruction can interrupt that operation. This is critical to the correct operation of many lock-free data structures and other concurrency paradigms.

What is meant by memory alignment?

Alignment refers to the arrangement of data in memory, and specifically deals with the issue of accessing data as proper units of information from main memory. First we must conceptualize main memory as a contiguous block of consecutive memory locations. Each location contains a fixed number of bits.

What does 4 byte aligned mean?

For instance, in a 32-bit architecture, the data may be aligned if the data is stored in four consecutive bytes and the first byte lies on a 4-byte boundary. Data alignment is the aligning of elements according to their natural alignment.


2 Answers

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.

like image 183
Sergey Kalinichenko Avatar answered Nov 15 '22 22:11

Sergey Kalinichenko


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

like image 44
NPE Avatar answered Nov 15 '22 21:11

NPE