i want to serialize my class but i have two problem.
first, i'll show my class.
namespace CommonData
{
enum DataType { SHPERICAL, COORDINATE, VIEW };
class Data
{
public:
virtual int serialize(char** param) = 0;
protected:
//every size is byte unit
int initialize(char** param, int size);
int fill(char** param, int start, int size, void* src);
private:
DataType _type;
};
class CoordinateData : public Data
{
public:
int serialize(char** param) override;
private:
int _x, _y, _z;
};
};
and this is cpp code
int Data::initialize(char** param, int size)
{
*param = new char[size];
cout << "size : " << size << endl;
return fill(param, 0, sizeof(DataType), &_type);
}
int Data::fill(char** param, int start, int size, void* src)
{
char* p = reinterpret_cast<char*>(src);
int i = 0;
while(i < size)
{
cout << "i : " << i << endl;
cout << "*(p + i) : " << (int)*(p + i) << endl;
*param[start + i] = *(p + i);
cout << "*param[start + i] : " << (int)*param[start + i] << endl;
i++;
cout << "==============" << endl;
}
return start + size;
}
int CoordinateData::serialize(char** param)
{
int end = 0;
end = initialize(param, sizeof(CoordinateData));
return end;
}
so if i start main code like this
int main()
{
char* arr = nullptr;
CommonData::CoordinateData _coor(1, 2, 3);
int size = _coor.serialize(&arr);
}
the console output is like this.
size : 20
i : 0
*(p + i) : 1
*param[start + i] : 1
==============
i : 1
*(p + i) : 0
*param[start + i] : 0
==============
i : 2
*(p + i) : 0
my first question is why the size of CoordinateData class is 20? i was predicted it will be 16(enum DataType _type, int _x, _y, _z -> 4 * 4 = 16 byte)
and second is fill function isn't working. i was remove some print functions but when i check to access at *param[start + i = 2], it is possible with garbage value, but when i run main code, they finished like that.
i heard c++'s accessing raw memory address is possible at every code without warrant about program's safety. so it can't be throw out of memory error, and i thought that char* arr is heap memory so it wouldn't be access at memory of code or data area, but it just shut down. why this happened?