I have a class whose object I pass through the socket via read() and write() . Among the class fields are standard type fields ( int and char ) and a field of type std::string .

I initialize the fields of the class, the field of the string type initializes with a string constant (maybe this is important). After transferring to the server, I transfer the field values ​​to the terminal. All fields are displayed correctly, but when I display a string field, a segmentation error occurs.

Therefore, the question is: how to transfer the type of string so that it is displayed correctly?

  • Are you passing and accepting a link / pointer to an instance of an object? - PinkTux
  • @PinkTux I pass a pointer to an object, and what I accept is rather a question to the read () function - Shadr
  • So you can not do. And even if an object contains only generic types, it makes sense to write separate functions for their reception and restoration. And the reasons for this are in bulk, starting with the banal different architecture on the client and server ... - PinkTux

2 answers 2

You need to pass its contents as a C-string, and by accepting, restore the string from this value.

Sort of

 string s; ... int l = s.length()+1; write(&l,sizeof(l)); write(s.c_str(),l); 

on the other hand

 string s; int l; read(&l,sizeof(l)); char * buf = new char[l]; read(buf,l); s = buf; delete[] buf; 

Like that...

  • Instead of int it is better to use types with a fixed length <cstdint> , otherwise the client with the server may have different sizes for int . - αλεχολυτ

Only the so-called POD types can be transmitted as raw data. Those. for which it is enough to copy sizeof(T) bytes to get a full copy of the object. std::string does not belong to such types. To properly transfer it over the network, you must convert it to a sequence of POD types. For example, first pass the length of the string in size() bytes, and then successively all data() bytes. After that, on the receiving side, form a new std::string object from this data using the appropriate constructor.

For more information, see the concept of "serialization".