-1

While doing some experiment on serialization, I noticed that my object name is lost when the object is retrieved. Would you please show me what is going on?

void nDB::serialize(macro* myMacro) {
    ofstream ar("macro.dat", ios::binary);
    ar.write((char*)myMacro,sizeof(*myMacro));
}

macro* nDB::deserialize() {
    macro* tmp_macro = (macro*)safemalloc(sizeof(macro));
    ifstream ar("macro.dat", ios::binary);
    ar.read((char*)tmp_macro,sizeof(*tmp_macro));
    printf("My macro name is %s\n",tmp_macro->get_name());
    return tmp_macro;
}

And this is what my output is

My macro name is \uffffs\uffff>

Thank you very much,

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Binh Van Pham
  • 111
  • 10

2 Answers2

2

What you are doing is undefined behavior.

You should not be using direct memory manipulation (and especially malloc and free) in C++, unless manipulating C-like structures (and still...).

For serialization and deserialization, you need a proper library (or to code one yourself, but you don't seem to have the necessary expertise yet).

I would recommend using Boost.Serialization.

But before that, I would recommend reading a C++ primer book (check out the list compiled here). You are not using idiomatic C++, you are using C-like idioms. This will bite you.

Community
  • 1
  • 1
Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
0

You are only storing the static memory for your object. Any dynamically allocated memory your object uses (such as std::string, std::vector or anything allocated with malloc, or new) will not be saved since they are located on the heap. You have to serialize and deserialize all dynamically allocated memory as well.

David Brown
  • 13,336
  • 4
  • 38
  • 55
  • @Binh The [C++ Middleware Writer](http://webEbenezer.net) takes care of these details. –  Mar 23 '12 at 03:22
  • Hi David, I understand this. However, my object name is statically allocated, as well as one other attribute called block. However, I was able to retrieve block which stored as a bit field but no name. I have no idea what is happening. If you have any idea would you please help. Thank you, – Binh Van Pham Mar 23 '12 at 20:11
  • How can I post the code now? This is the comment session, do I need to open another thread? – Binh Van Pham Mar 23 '12 at 20:24
  • @BinhVanPham Edit the original question – David Brown Mar 23 '12 at 22:56