What 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 selection and indentation are done using malloc() . Looking at the output, I see that the starting address is a multiple of 8. Are there any other rules?

+6
source share
3 answers

According to this documentation page ,

the address of the block returned by malloc or realloc on the GNU system is always a multiple of eight (or sixteen on 64-bit systems).

In general, malloc implementations are systemic. All of them save memory for their own accounting work (for example, the actual length of the allocated block) in order to be able to correctly free this memory when calling free . If you need to align to a specific border, use other functions, such as posix_memalign .

+8
source

The only standard rule is that the address returned by malloc will be properly aligned to hold any variable. What exactly this means is platform dependent (since alignment requirements vary from platform to platform).

+4
source

For a 32-bit Linux system:
When malloc () allocates memory, it allocates 8 in number (pad 8) and allocates an additional 8 bytes for accounting.

For instance:

malloc (10) and malloc (12) will allocate 24 bytes of memory (16 bytes after filling + 8 Bytes for accounting).

malloc () does padding because the returned addresses will be a multiple of eight, and therefore will be valid for pointers of any type. Accounting 8 bytes is used when we call a free function. The storage bytes store the length of the allocated memory.

0
source

Source: https://habr.com/ru/post/904154/


All Articles