I am trying to implement a generic serialization method, that I would like to use to serialize/ de-serialize generic custom structures with the following code:
#include <string>
#include <iostream>
class MessageSerializer
{
public:
MessageSerializer(){}
~MessageSerializer(){}
template <typename Data>
std::string serialize(const Data data)
{
const char* lpData = reinterpret_cast<const char*>(&data);
std::string serializedData( lpData, sizeof(data));
return serializedData;
}
template <typename Data>
void deSerialize( const std::string &serializedData, Data &deserializedObject )
{
const size_t serializedDataSize = serializedData.size();
const size_t outputDataSize = sizeof(Data);
if ( serializedDataSize != outputDataSize ){
std::cout << "Failed size check" << std::endl;
}
std::copy(std::begin(serializedData), std::end(serializedData), reinterpret_cast<char*>(&deserializedObject));
}
};
#pragma pack(push, 1)
struct testStruct
{
testStruct(int a, double f, std::string text, char c) : _a(a), _f(f), _text(text), _c(c){}
testStruct(){}
int _a;
double _f;
std::string _text;
char _c;
};
#pragma pack(pop) ```
When using it in my main:
#include "serializer.hpp"
#include <iostream>
#include <string>
int main ()
{
MessageSerializer ser;
testStruct sender(1, 345.234, "this is a test string", 'h');
testStruct receiver;
std::string msg = ser.serialize(sender);
std::cout <<"serialized: " << msg << std::endl;
std::cout << "-------------" << std::endl;
ser.deSerialize(msg, receiver);
std::cout << "received content: \na= " << receiver._a
<< "\nf: " << receiver._f
<< "\ntext: " << receiver._text
<< "\nc: " << receiver._c << std::endl;
return 0;
}
It seems to work, after my main ends I end up receiving the following error message:
free(): double free detected in tcache 2 Aborted (core dumped)
I seem unable to find the exact cause of that. After some research I understand that apparently a resource is being freed twice that has not been allocated a second time, but I am not allocating any memory on the heap anywhere at all.
Can anybody help me understand the cause of my problem, please?