3

If i have a structure like

struct MixedStructure{
char a;
short b;
int c;
char d;
};

Padding will come to effect.

What I want to know, is if there is a problem sending such a structure over the network.

I mean, this structure actually has 12 bytes (instead of 8) because of padding. If at the other end there is used another padding scheme ( or none), what would be the implications ?

coredump
  • 3,017
  • 6
  • 35
  • 53

2 Answers2

2

If you are using GCC then use __packed__ attribute:

#define PACKED __attribute__((__packed__))
struct PACKED MixedStructure { ... };

If you are on Windows the use pragma:

#pragma pack(push, 1)
struct MixedStructure { ... };
#pragma pack(pop)

If you want to be aligned you can also use explicit padding:

#include <stdint.h>
#define PACKED __attribute__((__packed__))
struct PACKED MixedStructure {
    int8_t a;
    int8_t pad0; /* added for alignment */
    int16_t b;
    int32_t c;
    int8_t d;
    int8_t pad1[3]; /* added for alignment */
};

I also recommend using explicit-width types as above.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
2

That's not your only problem. How do you know the sizeof(int) or sizeof(short) is going to be consistent between the two boxs that build that struct?

Most compilers have ways to specify fixed-size variables (ie uint32_t). To answer your specific question, most compilers also have ways to specify packing.

Overlaying a struct onto a buffer of bytes is a very common idiom in high-performance network programming but can be frought with peril. You'll also need to learn about how this idiom violates strict-aliasing and what endianess is.

I know that in very high-performance situations this is the best option. Just be very very careful and test very well between all the potential hosts that might communicate together. If you don't need this kind of performance, check out something like google's protocol buffers for transmitting data in a pretty performant way that lets you avoid knowing about packing/endianess/etc.

Community
  • 1
  • 1
Doug T.
  • 64,223
  • 27
  • 138
  • 202
  • First of all, thank you for your answer. I know about endianess and packing. After your response, I would ask, how do you properly send any kind of data over the network to all kind of potential hosts ? – coredump Sep 06 '12 at 15:38