Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Result of calling strcpy is different than expected

Tags:

c

strcpy

#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?

like image 200
Blood-HaZaRd Avatar asked Dec 04 '22 04:12

Blood-HaZaRd


1 Answers

strcpy(src, &src[1]); is undefined behavior:

C11 §7.24.2.3 The strcpy function

The strcpy function copies the string pointed to by s2 (including the terminating null character) into the array pointed to by s1. 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.

like image 73
Yu Hao Avatar answered Dec 22 '22 17:12

Yu Hao