Memory size for program

Thread Starter

mukesh1

Joined Mar 22, 2020
32
integer take four bytes, char takes one byte and float take four bytes. Total are three variables that occupy nine bytes But when I store these three variables through the structure, the program size is 12 bytes. I do not understand what does store in 3 bytes of memory

Code:
#include <stdio.h>
struct p
{
    int x;
    char y;
    float z;
}v;

int main()
{
    printf("size of structure = %d", sizeof(v))
    return 0;
}
 

ZCochran98

Joined Jul 24, 2018
77
It's most likely because the compiler adds "padding" to a structure to get the bytes to align properly. Because 9 is not divisible by 4 (most machines read/write memory accesses in chunks of 32 bits, or 4 bytes, called a "word," so that's why it's 4 and not 2. Even in 64-bit machines like mine it considers one word to be 4 bytes, not 8 - that's because the modern C compiler, like other languages, was initially designed for 32-bit machines, though 16-bit variations do exist like for Arduino), it will pad the structure size until it fits into the memory blocks "nicely" to avoid alignment issues. It makes it easier on the processor to pull in data. In this particular case, it needs to fit into 3 words (because 2 isn't enough), which comes out to 12 bytes. The compiler can get away with storing data like "char" or "byte" in a single byte because most machines are "byte-addressable," so the processor can actually reference an individual byte. But to make structs easy for the machine, because they typically are collections of data, the compiler forces them to fit into some number of words, rather than bytes.

tl;dr: the compiler forces the struct into 12 bytes (or 3 words) instead of 9 due to memory architecture and to make it easy for the CPU to grab the chunks of data. Those extra 3 bytes are full of unusable 0s.

There may (or may not) be a way to force it to fit into exactly 9 bytes, but I don't remember if you actually can.

For more information if you're curious, check out these two references:
Structure Padding in C
Is sizeof for a struct equal to the sum of sizeof of each member

Hope that helps!
 

MrChips

Joined Oct 2, 2009
21,302
integer is not necessarily 4 bytes. It can also be 2 bytes.
It depends on the processor model and the compiler.

Regardless, struct will be assigned memory to make it easier to reserve and access storage for the structure.
If four bytes have been assigned to char then only one byte is used for the value. The unused bytes are initialized to zero.
 

xox

Joined Sep 8, 2017
456
We call this structure padding. How can we remove it in structure ?
The C language doesn't actually specify how this is to be done. So you have to rely on compiler extensions.

That said, most do seem to support this syntax:

Code:
#pragma pack(push, 1)
struct abc
{
 int a, b, c;
};
#pragma pack(pop)
 
Top