C Valgrind - Source and destination overlap in memcpy
Solution 1
You have to use memmove
instead of memcpy
if the source and destination memory blocks overlap.
Solution 2
You are telling memcpy()
to copy 69141077 bytes of data. This looks to be much bigger than the size you have actually allocated in offset
(unless those strings are really huge).
So, it's a buffer overflow. Check that the contents of msg->content.value->datasize
match the size you're calculating when allocating offset
.
Solution 3
The man page for memcpy()
says:
The memcpy() function copies n bytes from memory area s2 to memory area s1. If s1 and s2 overlap, behavior is undefined. Applications in which s1 and s2 might overlap should use memmove(3) instead.
User Conscious
Updated on June 25, 2022Comments
-
User Conscious about 2 years
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