I've been handed legacy code that I need to insert a new feature into... For the feature I am populating the message struct that was provided to me and then pack it into a vector. However I am running into issues where the data isn't making it all the way over in one piece. I know that my struct is causing the issue since when I so a sizeof(struct) I get an incorrect size.
struct fault
{
std::string n, d;
bool rec;
int sev;
std::vector diagData;
}
void MsgPack::pack(std::string n, std::string d, bool r, int s)
{
fault Msg;
fault.n = n;
fault.d = d;
fault.rec = r;
fault.sev = s;
std::size_t size = sizeof(fault); //ALWAYS returns 48 no matter how large strings are.
unsigned char* data;
memcpy(data, (const unsigned char*)&fault,size);
std::vector<char> p;
for(int i=0;i<size; i++)
{
p.push_back(data[i]);
}
sendMsg(p);
}
So I know there are several problems with this code, from the push_back, to the always returning 48... My questions are as follows:
- I know that I can define the struct to contain chars that are predefined in size; however, the API call that I'm trying to make takes a string as an argument. I want to allow for the user to write anything that need/want and not box them in. Is there a way to keep the strings in the struct?
- Is there a better way to do the push_back? I know that it iterating over 48 8byte chunks will either put too much or too little into the vector.
- Just general coding practices and advice... Its been about 5yrs since I coded last so I am very rusty. I usually don't touch code so please go gentle on me :).