Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Valgrind - Source and destination overlap in memcpy

Tags:

c

valgrind

memcpy

I'm new to c programming and I'm writing a simple client server application. I get this message:

 Source and destination overlap in memcpy(0x41f0beb, 0x41f0258, 69141077)
    ==9522==    at 0x402D9A9: memcpy (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
    ==9522==    by 0x8049C13: message_to_buffer (message.c:92)

Here is the specific code:

case CT_ENTRY://100
{
    int c=(2+2+4+strlen(msg->content.entry->key)-1+4+4+strlen(msg->content.entry->value->data));
    char *offset=malloc(c);
    *msg_buf=offset;
    memcpy(offset,&opcode,2);
    offset+=2;
    memcpy(offset,&ctype,2 );
    offset+=2;
    int ks=strlen(msg->content.entry->key);
    int ksc=host_to_net(ks);
    memcpy(offset,&ksc,4);
    offset+=4;
    memcpy(offset, msg->content.entry->key, ks);
    offset+=ks;
    int l=host_to_net(get_time());
    memcpy(offset,&l,4);
    offset+=4;
    int ds=host_to_net(msg->content.entry->value->datasize);
    memcpy(offset,&ds,4);
    offset+=4;

    // this line here!
    memcpy(offset,msg->content.entry->value->data, msg->content.value->datasize);

    return c;
    break;

The offending line is

memcpy(offset,msg->content.entry->value->data, msg->content.value->datasize);

Can anyone please explain why this is happening? Thanks

like image 407
User Conscious Avatar asked Dec 05 '12 10:12

User Conscious


People also ask

Can memcpy overlap?

memcpy() doesn't support overlapping memory. This allows for optimizations that won't work if the buffers do overlap.

What is memory overlapping in memcpy?

The difference between memcpy and memmove is that. in memmove , the source memory of specified size is copied into buffer and then moved to destination. So if the memory is overlapping, there are no side effects. in case of memcpy() , there is no extra buffer taken for source memory.


1 Answers

You have to use memmove instead of memcpy if the source and destination memory blocks overlap.

like image 171
Juraj Blaho Avatar answered Oct 10 '22 20:10

Juraj Blaho