0

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:

  1. 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?
  2. 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.
  3. 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 :).
Sharki
  • 375
  • 2
  • 14
  • `sizeof` does not do what you think it does. You will be surprised to learn that `sizeof` of a `std::string` will give you the same value whether the string is empty, or contains the entire collected text of "Harry Potter". The issue is not `push_back`, but a more fundamental fact that `sizeof` does not, I repeat, does not give you the "size" of a `std::string`'s ***contents***. – Sam Varshavchik Nov 09 '21 at 21:07
  • The `sizeof` a type is always independent on the actual value of the type (here the strings in the `fault`). Anything else would basically break C++ – n314159 Nov 09 '21 at 21:08
  • So what would the solution to that be? I understand that that is the issue, but I am not seeing how to resolve it. – Sharki Nov 09 '21 at 21:43

0 Answers0