-5
#include<stdio.h>
#include<string.h>

int main(void)
{
    char input[10] = "I love you";
    char result[5] = "love";

    strcpy(result, input);
    printf("Copy: %s", result);

    return 0;
}

enter image description here

enter image description here

This is my code. And First picture is my result. Second picture is lecture's result. Why Two results are different??

Acorn
  • 24,970
  • 5
  • 40
  • 69
  • 2
    I see both pictures printing "I love you". The results looks the same for me. What do you mean "different"? – John Park Aug 17 '20 at 03:57
  • 3
    `strcpy(result, input);` 1) `input` is not nul-terminated. 2) `result` buffer is too small. – dxiv Aug 17 '20 at 03:58
  • From the strcpy man page: The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. As dxiv said, "result" is too small (needs to be 11 characters long. As should "input". I believe the initialisation as above will also lead to a 1 byte buffer overwrite. – Chris Aug 17 '20 at 04:15
  • 1
    @Chris Regarding your last point, the initialization itself does not (and can never) overrun the buffer. What happens is that `input` is initialized to the 10 characters of text and the terminating `\0` is omitted. This is the C behavior, and would normally trigger a warning with most compilers. In C++ such initialization is illegal and should generate an error. See for example [Why “initializer-string for array of chars is too long” compiles fine in C & not in C++?](https://stackoverflow.com/questions/28433862/why-initializer-string-for-array-of-chars-is-too-long-compiles-fine-in-c-not). – dxiv Aug 17 '20 at 04:43
  • Get a better lecturer, seriously! There is **nothing** to be learnt from this one. – Antti Haapala -- Слава Україні Aug 17 '20 at 05:04
  • Thanks dxiv. I was not aware of that subtly. That is a really nasty one either way if compiler warnings are disabled (or ignored). – Chris Aug 17 '20 at 05:33

1 Answers1

4

Why Two results are different??

With strcpy(result, input);, result lacks enough room for input. The result is undefined behavior (UB). Also input does not allow space for the trailing null character.

Try:

char input[11] = "I love you"; 
char result[11] /* or more */ = "love";
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256