Chebz
Chebz

Reputation: 1395

C++ platform compatibility

An object foo is written to a new file on platform 1 as:

write( file, &myFoo, sizeof(struct foo) );

...and then read on platform 2 using:

read(file, &myFoo, filesize(file) );

The foo object has the following definition:

struct foo
{
    char  a;
    int   b; 
    long  c;
    char* d;
};

What kind of issues might arise when loading foo on platform 2?

Upvotes: 4

Views: 436

Answers (3)

user3290770
user3290770

Reputation: 5

i think, you have to use that pack pragma to ensure there are no padding. otherwise char will have 4 bytes in size depending on the default padding method.

char* this address pointer can have 32bits on 32bit machine but 64bits on 64bit machine. So store a pointer directly out is nonsense.

The last one is endian.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182639

When you do this you need to watch out for:

  • Data type sizes (char is the only one you can trust)
  • Alignment / padding
  • Endianness
  • Pointing to invalid memory
  • Floating point representation
  • ASCII vs EBCDIC ? (yeah, seriously ?)
  • Probably others

Upvotes: 8

Bo Persson
Bo Persson

Reputation: 92261

Every kind of issue!

We don't know if char, int, long or char* are the same size on different platforms.

And what happened to the stuff d pointed to?

There might also be padding between the members, which could differ between platforms. Big endian and little ending systems would store the bytes of integers and pointers in different order. If you are really unlucky, there might be a middle endian system as well.

Upvotes: 12

Related Questions