0

I am trying to understand the process by which I can serialize and de-serialize data in C. I wrote code that I believe should write a simple struct to a char buffer.

#include <packet.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>


typedef struct
{
        int A;
        int B;
        int C;
}test_packet;

int main(int argc, char** argv)
{
        test_packet p;
        p.A = 1;
        p.B = 2;
        p.C = 3;

        char buffer [sizeof(p)];
        memcpy(buffer, &p, sizeof(p));
        printf("%x \n", buffer);

        return 0;
}

However, when I run this code, since the struct being serialized is statically coded, I expect to see a buffer that's the same each time. I don't, I see a buffer that appears to be full of random data:

./SerializePacket
41bf5380
./SerializePacket
d89fc790
./SerializePacket
aea2c00
./SerializePacket
d355dc10

Can anyone alleviate me of my ignorance here?

Kevin John
  • 71
  • 8

1 Answers1

0

What you are printing is a pointer, the address of the buffer.

About serialization: you are copying the struct over the buffer, with padding and all. That it's not portable, unless you serialize and de-serialize in the same computer. To serialize a struct directly copying to the buffer, you should use packed structures (see: What is a "packed" structure in C?, https://en.wikipedia.org/wiki/Data_structure_alignment). Also, using an integer of fixed size is preferred for serialized data, for example, uint16_t for a 16 bits unsigned integer.

Mance Rayder
  • 353
  • 2
  • 10
  • 1
    "...unless you serialize / deserialize it on the same computer with both the code writing and the code reading having been compiled by exaclty the same compiler in the same version..." – Michael Beer Jun 29 '18 at 21:36
  • 1
    Also, speaking of portability: Mind the endianness of your serialized data. *Don't use packed structures unless they conain octets only* - they are not portable as their members' endianness will differ on different architectures. – Michael Beer Jun 29 '18 at 21:40