Archived

This topic is now archived and is closed to further replies.

Silverbolter

malloc docs... and alignment

Recommended Posts

from this page: http://www.gnu.org/software/libc/manual/html_mono/libc.html#Aligned%20Memory%20Blocks "The block that malloc gives you is guaranteed to be aligned so that it can hold any type of data. In the GNU system" What does being aligned so it can hold any type of data mean? Does this mean if I do pointer = malloc(sizeof(char)); then later if I want to put a double at location pointed to by pointer that would be OK? So basically does malloc give you 8bytes every time you allocate something, so it can potentially store everything?

Share this post


Link to post
Share on other sites
aligned means in blocks of memory that your computer is fast at handling. so you have a 32bit processor (unless you have a 64bit, i.e. the AMD), which means that malloc will return a block of memory in multiples of that. so sizeof(char) will be 32bits as will sizeof(double), etc. any sizeof(structType) will return a size big enough to hold your struct plus any extra number of bits needed to make that block be a multiple of 32. while this may seem a waste of memory, doing otherwise makes your computer much slower at acessing memory and so is not desireable.

-me

[edited by - Palidine on January 16, 2004 2:33:09 PM]

Share this post


Link to post
Share on other sites
No, it basically means that the address is always a multiple of the greatest alignment of a primitive type. For an 32 bit x86 processor, I believe that''s 8 bytes, for the size of a double. If you tried to put a double in, for example, memory address 0x10000003, then you''d have troubles accessing it because it isn''t properly aligned. malloc() might only allocate 4 bytes with a call of malloc(1), but the address it returns will be a multiple of 8 (again assuming x86 processor).

Share this post


Link to post
Share on other sites
So byte alignment means the address is a multiple of not the block returned to the user. This makes more sense to be because otherwise we''d always return 8 byte blocks when the user needs only 4. Which seems quite a waste.

Thanks!

Share this post


Link to post
Share on other sites
Hold on to your hat.... depending on how your version of glibc was built it might actually return 12 bytes when you request 4. IIRC, this depends both on the glibc version, processor and the various flags passed when building libc. On the other hand, some versions will return only the 4 that were requested.

Share this post


Link to post
Share on other sites
I''m not sure if the malloc() behaviour for your system would be listed in the man pages. There is a way to find out how your particular system behaves with a test program.

void * ptr = malloc(1);
size_t s = malloc_usable_size(ptr);
free(ptr);

s should then contain the minimum size that your glibc version will allocate through malloc().

Share this post


Link to post
Share on other sites