Strcpy call result is different than expected

#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 does this program print " 23556" when compiling with gcc 4.7.2?

+4
source share
3 answers

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

C11 ยง7.24.2.3 Function strcpy

The function strcpycopies the string that it points to s2(including the terminating null character) into the array that it points to s1. If copying occurs between objects that overlap, the behavior is undefined.

, memcpy ( memmove). . C FAQ: memcpy memmove.

+12

undefined. memmove. memmove .

memmove(src, &src[1], strlen(&src[1]) + 1) ;  // + 1 for copying the terminating zero
+2

ISO/IEC 9899: TC3 (c99)

7.21.2.3 strcpy

1

#include <string.h>

char *strncpy(char * restrict s1, const char * restrict s2, size_t n);

2 strcpy , s2 ( ) , s1. , , undefined.

, , undefined behaving;)

J.2

undefined , :

undefined :

[...]

- When you try to copy an object to an overlapping object using the library, a function other than explicitly allowed (for example, memmove) (section 7).

+2
source

Source: https://habr.com/ru/post/1568137/


All Articles