Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Allocation for Structure Elements

Tags:

c

I have read that structure members needn't be contiguous in memory. Does this mean they can be in arbitrary places in memory just like they are different variables? If this is so, wouldn't using malloc for allocating space for a structure waste much storage?

like image 312
Insignificant Person Avatar asked Apr 19 '26 00:04

Insignificant Person


2 Answers

While members are not necessarily contiguous, they're not in arbitrary memory locations either. Take, for example, the following definition:

struct MyStruct
{
    char foo;
    int  bar;
};

Assuming sizeof(int) == 4, then foo will be at offset 0 and bar at offset 4 (to be properly aligned). So the whole structure will be 8 bytes, even though it could fit in 5. However, these offsets will always be the same for every instance of this structure. So to answer your question about malloc, no, it will not waste space.

As far as separate variables, yes, they may be located at different locations in memory, but the whole point of structures is to group related variables. Therefore, all members of the same struct instance will be closely grouped together.

like image 122
Drew McGowen Avatar answered Apr 21 '26 13:04

Drew McGowen


Depending on the CPU architecture it may be necessary for the structure members to be correctly aligned, eg the address of a 4 byte member should be divisible by 4. Some CPUs don't need such alignment, but many do. Some CPUs will crash if you attempt to do stuff with improperly aligned data, others will cope but access to improperly aligned data will be much slower.

Assembler programmers need to worry about this issue, but C programmers can generally leave the messy details to the compiler. But it means that structures can include "invisible" padding to ensure proper alignment. This padding doesn't waste much space, and you can minimise the wasted space by good layout of your structure members. Note that this padding also happens to variables created on the stack for your functions.

For further info, please see Data structure alignment.

like image 32
PM 2Ring Avatar answered Apr 21 '26 14:04

PM 2Ring



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!