#include <stdio.h>
#include <string.h>
int main()
{
char src[]="123456";
strcpy(src, &src[1]);
printf("Final copied string : %s\n", src);
}
When I use the Visual Studio 6 Compiler it gives me the expected answer "23456".
How come this program prints "23556" when compiled with gcc 4.7.2?
strcpy(src, &src[1]); is undefined behavior:
C11 §7.24.2.3 The
strcpyfunctionThe
strcpyfunction copies the string pointed to bys2(including the terminating null character) into the array pointed to bys1. If copying takes place between objects that overlap, the behavior is undefined.
By the way, memcpy is similar (but not memmove). See C FAQ: What's the difference between memcpy and memmove.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With