(sizeof) char always returns 1 in 32 bit GCC compiler.
But since the basic block size in 32 bit compiler is 4, How does char occup
Because of optimisation padding is added so size of an object is 1, 2 or n*4 bytes (or something like that, talking about x86). That's why there is added padding to 5-byte object and to 1-byte not. Single char
doesn't have to be padded, it can be allocated on 1 byte, we can store it on space allocated with malloc(1)
. st
cannot be stored on space allocated with malloc(5)
because when st
struct is being copied whole 8 bytes are being copied.
First of all, sizeof
returns a number of bytes, not bits. sizeof(char) == 1
tells you that a char
is eight bits (one byte) long. All of the fundamental data types in C are at least one byte long.
Your structure returns a size of 8. This is a sum of three things: the size of the int
, the size of the char
(which we know is 1
), and the size of any extra padding that the compiler added to the structure. Since many implementations use a 4-byte int
, this would imply that your compiler is adding 3 bytes of padding to your structure. Most likely this is added after the char
in order to make the size of the structure a multiple of 4 (a 32-bit CPU access data most efficiently in 32-bit chunks, and 32 bits is four bytes).
Edit: Just because the block size is four bytes doesn't mean that a data type can't be smaller than four bytes. When the CPU loads a one-byte char
into a 32-bit register, the value will be sign-extended automatically (by the hardware) to make it fill the register. The CPU is smart enough to handle data in N-byte increments (where N is a power of 2), as long as it isn't larger than the register. When storing the data on disk or in memory, there is no reason to store every char
as four bytes. The char
in your structure happened to look like it was four bytes long because of the padding added after it. If you changed your structure to have two char
variables instead of one, you should see that the size of the structure is the same (you added an extra byte of data, and the compiler added one fewer byte of padding).