Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This cast is very dangerous as you have allocated some raw memory and then treated it as an initialized object of a non-POD class type. This is likely to cause a crash at some point.</p> <pre><code>Packet* p = (Packet *) malloc(8 + 30); </code></pre> <p>Looking at your code, I assume that you want to write out a sequence of bytes from the <code>Packet</code> object that the seralize function is called on. In this case you have no need of a second packet object. You can create a vector of bytes of the appropriate size and then copy the data across.</p> <p>e.g.</p> <pre><code>void* Packet::Serialize(int size) { char* raw_data = new char[sizeof sender_id + sizeof sequence_number + data.size()]; char* p = raw_data; unsigned int tmp; tmp = htonl(sender_id); std::memcpy(p, &amp;tmp, sizeof tmp); p += sizeof tmp; tmp = htonl(sequence_number); std::memcpy(p, &amp;tmp, sizeof tmp); p += sizeof tmp; std::copy(data.begin(), data.end(), p); return raw_data; } </code></pre> <p>This may not be exactly what you intended as I'm not sure what the final object of your <code>size</code> parameter is and your interface is potentially unsafe as you return a pointer to raw data that I assume is supposed to be dynamically allocated. It is much safer to use an object that manages the lifetime of dynamically allocated memory then the caller doesn't have to guess whether and how to deallocate the memory.</p> <p>Also the caller has no way of knowing how much memory was allocated. This may not matter for deallocation but presumably if this buffer is to be copied or streamed then this information is needed.</p> <p>It may be better to return a <code>std::vector&lt;char&gt;</code> or to take one by reference, or even make the function a template and use an output iterator.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload