When I was recently working with structs in C, j-b pointed out how I could save memory by aligning the members properly. I had never come across such a thing before.
Consider a simple struct
struct
{
char a;
int b;
char c;
};
On a 32 bit system, it's common to assume the size of this struct is 6. However, compilers sometimes pad the members to align the data to the word boundary. This is because computer architecture entails that the processor may read memory at one word intervals. If the word size is 32 bits, then the processor can read 4 bytes from the 0th byte, 4th byte, 8th byte and so on.
This means that if a member is overlapping two "chunks" of words, then both of them need to be read. So if integer b starts at the 3rd byte, then two read operations on the 0th and 4th byte will be performed and the data will be aggregated. However, some architectures do not even allow such operations. Even if it does, it will take twice as long to read. Bummer.
So what happens above? The compiler just inserts junk into the struct to 'pad' it out and each member goes into it's own chunk. 4 + 4 + 4 = 12 bytes. That's half the memory wasted.
In the example struct, a smart optimization can be done. The two chars can be grouped. Now, the compiler can put both a and c on the same word. This couldn't be done before, because the members need to laid out sequentially. Now, the compiler will need to add only two padding bytes. The size now: 4 + 4 = 8 bytes. That's some good savings.
It is possible to force the compiler to either perform or not perform the alignment. For example, gcc has variable attributes that can force packing. But its important to remember that there will be performance losses and it may not work on all platforms.
Ok, so maybe this was basic computer architecture knowledge. To be fair, I didn't really pay attention in class!
Monday, December 28, 2009
Saturday, February 28, 2009
Codeplay
int a;
int p = 100;a = p/*2;
printf("%d",a);
int p = 100;a = p/*2;
printf("%d",a);
What's a?(C code)
Answer is that the code doesn't compile!
In a debugging contest I was organising, most people got that one wrong! It's basic stuff, but its so basic, most people don't recognize. I didn't spot it at first either. The whole contest thing was a very different experience for me at that point. I guess I had forgotten how much I enjoyed solving problems before I was bogged down by stupid details in life. I realised what I had missed. Codeplay.
Subscribe to:
Posts (Atom)