Why is memcpy not working correctly?

I have a class for an RDT header that contains information for implementing several reliable data transfer protocols. I need to attach this information (only 12 bytes) to my send buffer in order to pass it over the socket. I am trying to use memcpy for this, but for some reason it just leaves garbage in the buffer. Below is a line of code that does not work. (RDT_HDR_SIZE is defined as 12).

Defining the variables that are passed to this function.

char payload[] = "sample code sample code";
int payload_size = sizeof(payload) ; 
int pktsize = payload_size + sizeof( RdtHeader )+1 ; // 1 byte for NULL-terminated
char * send_buf = new char[pktsize];

A function with memcpy that has problems.

unsigned int Sender::CreateSegment( char * buf, 
         char payload[], int payload_size, unsigned long seqnum ) {
     RdtHeader * header = (RdtHeader *) buf; 
     // set rdt fields:
     header->ack = 0; 
     header->fin = 0; 
     header->ok = 0; 
     header->seq = seqnum; 
     header->win = 0;
     header->syn = 0;
     memcpy( buf+RDT_HDR_SIZE, payload, payload_size );

     return (payload_size + RDT_HDR_SIZE + 1);
}

If I take out RDT_HDR_SIZE, the payload is assigned properly for buf, however it destroys all the fields of my header. Any idea how to make this work?

Thank,

Eric R.

EDIT:

Here is the code for my RdtHeader class - maybe it will be useful.

class RdtHeader{    // 12-byte header 
public: 
//1-byte flags field
    u_char protocol:2;      // 2 bits: protocol type = 0 for RDT3, 1 for GBN, and 2 for STCP    
    u_char syn:1;           // 1 bit: SYN = 1 for connection setup  
    u_char fin:1;           // 1 bit: FIN = 1 for termination
    u_char ok:1;            // 1 bit: OK = 1 receiver agrees, SYN_OK or FIN_OK
    u_char reserved:3;      // 3 bits: unused

    u_char unused;          // 1-byte unused filed; 

    u_short win;            // 2-byte receiver window size (the number of packets)
    u_long seq;             // 4-byte sequence number
    u_long ack;             // 4-byte ack number
}; 
+3
3

, ?

printf( "%s\n", send_buf + sizeof(RdtHeader) );

?

...

printf( "%s\n", send_buf );

... ( ), win , .

hth.,

- Alf

+2

, sizeof (RdtHeader). ( , int), .

. , , , . , .

+2
memcpy(header + 1, payload, payload_size + 1);
return sizeof(*header) + payload_size + 1;
  • extra 1, , . , memcpy .
  • header memcpy, , , , buf. , ++ X * void *, .
0

Source: https://habr.com/ru/post/1769074/


All Articles