Unable to serialize and deserialize stack of strings in Qt/C++

182 views Asked by At

I have an application where I need some data to persist, so I thought about object serialization. I found a nice example here. Following it, this is what I came up with:

    std::stack <std::string> cards;
    cards.push("King of Hearts");
    std::ofstream ofs("<location>", std::ios::binary);
    ofs.write((char *)&cards, sizeof(cards));
    ofs.close();

Then I am trying to read the data:

    std::stack<std::string> inp;
    std::ifstream ifs("<same_location>", std::ios::binary);
    ifs.read((char *)&inp, sizeof(inp));

However the app is crashing at the last line (for some reason, due to my Qt settings, I am unable to debug currently). What can be the possible error, and how do I fix this?

2

There are 2 answers

0
bialpio On

Short answer is: you cannot serialize stack in the same way as the article describes. I'd say that you can only serialize PODs that way. The problem here is that the data you want to write is not stored continuously in the memory and by using ofs.write((char *)&cards, sizeof(cards)); you are not not taking into account the pointers to other places in the memory.

Try this experiment: how come that sizeof(cards) do not change when you add more and more data to it?

0
BlamKiwi On
  1. Your issue is that you're assuming properties about stack that aren't true. std::stack by default uses a deque as its backing structure so items are not contiguous in memory.
  2. You should never assume that data structures you don't own are safe for arbitrary serialization. In C++ the preferred paradigm is to use >> and << stream operators as transformations can take place.
  3. sizeof() only gets the size of an object in memory, not the size of any data pointers may point to. sizeof() to get the amount of items in a container will result in useless values.

To fix these issues you should write your own stream operators to serialize in a layout you know you have control over.