Segfault on delete after istream::read()

Pages: 12
Very good.

This is definitely good to know, in case I need to interface with other languages in the future.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <fstream>

#define WITH_VTABLE

struct A{
        int a;
#ifdef WITH_VTABLE
                virtual void f() { std::cout <<this->a<<std::endl; }
#endif
};

int main()
{
        std::cout <<sizeof(A)<<std::endl;

        A a;
        a.a = 0xA3;

        std::ofstream os;
#ifdef WITH_VTABLE
        os.open( "/tmp/with.bin" );
#else
        os.open( "/tmp/without.bin" );
#endif
        os.write( (char*) &a, sizeof( a )); 
        os.close();
}


hexdump /tmp/with.bin
hexdump /tmp/without.bin

shows the layout. Thank you so much for explaining!
Last edited on
Do not do that. Never serialize pointers.
I serialized the object A a

It just so happened that it had a vtbl pointer in it in the case where I left in WITH_VTABLE, which was educational, but shows exactly why we should only serialize PODs (because pointers have no meaning after serialization).

When I assign a.a to be 0xA3, I get:

/tmp$ hexdump with.bin
0000000 8c68 0804 00a3 0000
0000008
/tmp$ hexdump without.bin
0000000 00a3 0000
0000004

on a 32-bit Ubuntu box.

But what if I were serializing over a pipe and the box on the other side were also a 32-bit Ubuntu box with the same executable? I'm guessing that it would still fail because that 8c68 0804 is a pointer to some vtable in the code segment, which could be different even on different runs on the same machine? So that information would be useless.
Last edited on
Topic archived. No new replies allowed.
Pages: 12