Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padded structures using __attribute__(__packed__), is it really worth it?

Tags:

c

gcc

struct

gcc (GCC) 4.7.0
c89
x86_64

Hello,

I am wondering is it worth it using using the __attribute__ ((__packed__)) on structures. It seems to me that with it the structure will be smaller in size. Going by the test I have performed below. So using it would be an advantage in size.

A case for not using it, as it is not portable across other compilers. So for visual studio C++ this won't work. Plus other compilers as well.

Doesn't the compiler optimize the code? So really leaving it up to the compiler to decide what to do would be better for performance?

Would using the aligned attribute make any difference? __attribute__((packed, aligned(4))) When I added that it returned the size of 12.

Many thanks for any suggestions,

#include <stdio.h>

struct padded {
    int age;      /* 4                    */
    char initial; /* 1 + 3 padded bytes   */
    int weight;   /* 4     --> total = 12 */ 
};

struct __attribute__ ((__packed__)) unpadded {
    int age;      /* 4                  */
    char initial; /* 1                  */
    int weight;   /* 4    --> total = 9 */
};

int main(int argc, char **argv)
{
    struct padded padded_test;
    struct unpadded unpadded_test;

    printf("Padded   [ %ld ]\n", sizeof(struct padded));
    printf("Unpadded [ %ld ]\n", sizeof(struct unpadded));
    return 0;
}
like image 530
ant2009 Avatar asked Sep 06 '12 16:09

ant2009


1 Answers

Unaligned memory access can be horrendously slow on some architectures (e.g. ia64, sparc64). __attribute__((__packed__)) is principally intended for use where you're sending data over the wire and want to be sure of the layout; it's not worth trying to use it to save space in memory.

If you are considering using __attribute__((__packed__)) for wire transmission, think again; it doesn't handle endianness, and it's non-standard. Writing marshalling code yourself is safer, and using a library (e.g. Protocol Buffers) is smarter.

like image 58
ecatmur Avatar answered Sep 19 '22 12:09

ecatmur