Memory allocation for structural elements

I read that the members of a structure should not be contiguous in memory. Does this mean that they can be in arbitrary locations in memory in the same way that they are different variables? If so, wouldn't you use malloc to allocate storage space for a lot of storage structure?


source to share

2 answers

Although the members are not necessarily contiguous, they are 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 (for correct alignment). Thus, the entire structure will be 8 bytes, although it can fit into 5. However, these offsets will always be the same for every instance of this structure. So to answer your question about malloc

, no, it won't waste space.

As for individual variables, yes, they can be located in different places in memory, but the whole point of structures is to group together related variables. Therefore, all members of the same structure instance will be closely grouped.



Depending on the architecture of the CPU, it may be necessary for the structural members to be aligned correctly, for example, the address of a 4-byte member must be divisible by 4. Some CPUs do not need to be aligned, but many do. Some processors will crash if you try to make stuff with the wrong data, others will handle it, but accessing the wrong data will be much slower.

Assembly programmers need to worry about this problem, but C programmers can usually leave useless details to the compiler. But this means that structures can include "invisible" padding to ensure correct alignment. This add-on doesn't waste a lot of space and you can minimize wasted space with good layout of your struct members. Note that this addition also happens to variables created on the stack for your functions.

For more information, see Data Structure Mapping .



All Articles