char test[]={"abcde"};
char* test1={"xyz"};
memcpy(test+5,test1,3);
printf("%s",test);
I’m trying to grasp how exactly memcpy works and this is the example I’ve written so far.
This gives output as abcdexyz&vjunkcharacters
and the following message.
*** stack smashing detected ***: ./testcode terminated
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(__fortify_fail+0x45)[0xb7656dd5]
/lib/i386-linux-gnu/libc.so.6(+0xffd8a)[0xb7656d8a]
./testcode[0x8048797]
/lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf3)[0xb75704d3]
./testcode[0x80483a1]
What are the reasons behind this situation?
Root Cause:
Allocates enough memory space to store
5characters only.Copies the data pointed by
test1beyond the allocated memory space.Technically, writing beyond the bounds of an allocated memory in this fashion is Undefined Behavior, which means anything can happen.
What actually happens?
What actually happens here is
memcpycopies characters beyond the allocated memory thus overwritting theNULLterminator which marks ends of your character arraytest.Further,
printfreads the contents from starting address oftesttill it encounters a randomNULLthus printing out junk characters.Solution:
You should ensure that destination buffer has enough memory allocated before you perform the
memcpy. Since you intend to copy3characters, Your destination buffertestshould be atleast:You can simply use: