C - Problems retrieving data from the buffer. Possibly related to

I'm having difficulty retrieving data from a buffer using memcpy.

First, I memcpy some variables to the buffer:

int l1_connect(const char* hostname, int port) {
    // Variables to be stored in the buffer
    char *msg = "Hi, I'm a message"; // strlen(msg) == 17
    uint16_t sender_id = htons(1); // sizeof(sender_id) == 2
    uint16_t packet_size = htons(sizeof(packet_size)+sizeof(sender_id)+strlen(msg)); // sizeof(packet_size) == 2

    // Checking values
    printf("l1_connect():\nsender_id: %d, packet_size: %d\n\n", ntohs(sender_id), ntohs(packet_size));
    // sender_id == 1, packet_size == 21

    // The buffer
    char buf[100];

    // Copying everything
    memcpy(&buf, &sender_id, sizeof(sender_id));
    memcpy(&buf+sizeof(sender_id), &packet_size, sizeof(packet_size));
    memcpy(&buf+sizeof(sender_id)+sizeof(packet_size), &msg, strlen(msg));

    // Passing buf to another function
    int bytes_sent = l1_send(1, buf, sizeof(buf));
}

Then I try to extract this data (check before sending via UDP socket):

int l1_send( int device, const char* buf, int length ) {
    // Variables in which to store extracted data
    uint16_t id = 0;
    uint16_t size = 0;
    char msg[50];

    memcpy(&id, &buf, sizeof(id));
    memcpy(&size, &buf+sizeof(id), sizeof(size));

    int remaining = ntohs(size) - (sizeof(id) + sizeof(size));
    printf("l1_send():\nremaining: %d\n", remaining); // -37041

    // memcpy-ing with correct(?) offset
    memcpy(&msg, &buf+sizeof(id)+sizeof(size), 50);

    msg[49] = '\0';

    printf("id: %d\n", ntohs(id));      // 8372
    printf("size: %d\n", ntohs(size));  // 37045
    printf("msg: %s\n", msg);           //   $_ 

    return 0; // For now
}

As you can see, the values ​​are not quite what I expect. Can someone tell me what I am doing wrong?

+3
source share
2 answers

Your pointing math is wrong. You use &bufwhere you should just use buf. If this does not explain what is wrong, I cannot say anything:

#include <stdio.h>

int main(int argc, char **argv)
{
    char buff[100];
    printf("buff : %p\nbuff+10 : %p\n&buff+10 : %p\n", buff, buff+10, &buff+10);
    return 0;

}

Exit (obviously platform dependent)

buff : 0xbf87a8bc
buff+10 : 0xbf87a8c6
&buff+10 : 0xbf87aca4

. , , , &buf 100 char s; char. &buff + 10 ( ) : " 10- 100 , ". undefined .

Valgrind - , . .


, , . l1_send:

memcpy(&id, &buf, sizeof(id));
// this------^

, . , . , buf.

+6

:

memcpy(buf, &sender_id, sizeof(sender_id));
memcpy(buf + sizeof(sender_id), &packet_size, sizeof(packet_size));
memcpy(buf + sizeof(sender_id) + sizeof(packet_size), msg, strlen(msg));

, , this.

:

+3

All Articles