1

Searching all the web for ways to serialize data in C so I could send a struct over a TCP/IP socket, I couldn't find anything simple. But I think that this way, you can fix the positions of the bits in a packet and thus serialize it "de facto".

packet *datapkt = NULL;
datapkt = (packet*)malloc(PKT_SIZE); // Allocation of memory with this size
datapkt->field = data;
......
send(datapkt);
free(datapkt);

Can anyone tell me if is this a good idea? This far it's working in my project.

Thanks in advance!

Sanjo
  • 78
  • 8
  • 2
    There is a laundry list of reasons to exercise caution when pushing structures in memory-layout form across a wire to a foreign host, [endianness](https://en.wikipedia.org/wiki/Endianness) and platform [padding and packing](http://stackoverflow.com/questions/4306186/structure-padding-and-packing) being near the top of the list. If what you're doing is "working", make sure it is doing so by design, and not by chance. – WhozCraig Dec 28 '16 at 10:37

3 Answers3

0

There is a severe flaw in your approach. You have no influence on the memory layout of your structure. The compiler might add padding bytes between struc members. If you have different compilers and CPUs on both ends of the connection, your approach using a simple struct will fail. Not to mention different endianess on different hardware.

Therefore it's not a good idea.

Gerhardh
  • 11,688
  • 4
  • 17
  • 39
0

Using structs for serialization over local inter thread/process communications is okay under same compiler and compiling flags. But isn't good idea for network communications. clients on the network may have different CPU arch or operating system and there isn't any guarantee that memory allocation for struct members will be constant on different machines, for example sizeof(int) may differ in X86 and X86_64 or other architecture/compiler. the memory layout is defined by compiler and may vary on different machines even different operating systems, also paddings and endiannes are coming in and changes the memory layout too.

e.jahandar
  • 1,715
  • 12
  • 30
0

When doing this you have to consider two things:

1. Endianness
2. Compiler padding

The first point will make the data take on different form depending on the endianness of your system. This is a problem for types bigger than a byte.

For the second point you will need to make sure that the compiler is not adding any bytes between the members in your structure. This can be done with compiler pragmas.

MathiasE
  • 467
  • 3
  • 10