Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does c compiler allocate memory for structures?

Tags:

c

By studying structure lead me to a question that how structures are stored in the memory by compiler which means consider

struct 
{
      int number;
      char name[nam];
 }h;

what i want to know is how the members (here it is number and name) are stored (whether they are stored in sequence or stored in random place for instance if number is stored in address 2000 and name is stored in 2990) ?

like image 693
Hash Avatar asked Dec 20 '22 20:12

Hash


2 Answers

Memory is allocated in a sequence for structure members:

+------------+------------------+-----+-----+-----+-----+-----+-----+
|            |     ........     |     |     |     |     |     |     |
|            |                  |     |     |     |     |     |     |
+------------+--------+---------+-----+-----+-----+-----+-----+-----+
+            +        |       name[0]                             name[nam-1]
+------+-----+        |         +------------------+----------------+
       |              |                            |
       |              |                            |
       v              v                            v
    number         padding                      name[nam]

But, unlike arrays, the allocated memory for a structure may or may not be packed, i.e, there may be some padding after the allocated space of any member (but no padding is allowed before the first member).

like image 94
haccks Avatar answered Dec 22 '22 08:12

haccks


You may find the answer in Data structure alignment:

Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding. When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

like image 40
Rahul Tripathi Avatar answered Dec 22 '22 08:12

Rahul Tripathi