Unknown Exception in construction of boost::archive::text_iarchive from std::istringstream

Viewed 82

I seem to be getting an error in constructing a boost::archive::text_iarchive from a std::istringstream

#include <vector>
#include <string>
#include <thread>
#include <atomic>
#include <iostream>
#include <unordered_map>
#include <functional>
#include <sstream>

#include "boost/asio.hpp"
#include "boost/bind.hpp"
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

int main() {


    std::vector<char> readBuffer_(8, 'x');


    std::string archive_data(&readBuffer_[0], readBuffer_.size());
    std::istringstream archive_stream(archive_data);
    if (archive_stream) {
        std::cout << "functioning" << std::endl;
    }
    boost::archive::text_iarchive archive(archive_stream);
    std::cout << "woop" << std::endl;
}

What could be the problem?

1 Answers

The code gets an exception because the input data xxxxxxxx is illegal to deserialization.

The doc for input_stream_error:

An error has occured during stream input or ouput. Aside from the common situations such as a corrupted or truncated input file, there are several less obvious ones that sometimes occur. This includes an attempt to read past the end of the file. Text files need a terminating new line character at the end of the file which is appended when the archive destructor is invoked. Be sure that an output archive on a stream is destroyed before opening an input archive on that same stream. That is, rather than using something like

You may verify it by replacing the input string to a valid serializaed content:

#include <array>
#include <atomic>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <functional>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>

int main() {
  std::istringstream archive_stream(
      "22 serialization::archive 9 3 0 1 3 5 0 0 2 0 0 0 1 3 one 2 3 two");
  if (archive_stream) {
    std::cout << "functioning" << std::endl;
  }
  try {
    boost::archive::text_iarchive archive(archive_stream);
  } catch (const std::exception& e) {
    std::cout << "except hit:" << e.what() << std::endl;
  }
  std::cout << "woop" << std::endl;
}

A related question to see the boost serialization format details. Generally, we should deserialize the content generated from boost realization results to avoid such kinds of errors.

Add we should catch the exception to make our program robust, there are several reasons to get corrupted data and get the deserialization exception:

  • disk data corruption
  • network transmission error
  • Other process/module of your system have bugs
Related