Can I copy a string in an empty string?

后端 未结 3 655
温柔的废话
温柔的废话 2021-01-25 13:31

Suppose I do like this to copy the string.

char str[] = \"\";
char *str2 = \"abc\";
strcpy(str, str2);
printf(\"%s\", str);  // \"abc\"
printf(\"%d\", strlen(str         


        
3条回答
  •  囚心锁ツ
    2021-01-25 13:43

    This code is definitely causing a stack problem, though with such a small string, you are not seeing the issue. Take, for example, the following:

    #include 
    #include 
    #include 
    
    int main()
    {
            char str[] = "";
            char *str2 = "A really, really, really, really, really, really loooooooooooooooonnnnnnnnnnnnnnnnng string.";
            strcpy(str, str2);
            printf("%s\n", str);
            printf("%d\n", strlen(str));
            return 0;
    }
    

    A contrived example, yes, but the result of running this is:

    A really, really, really, really, really, really loooooooooooooooonnnnnnnnnnnnnnnnng string.
    92
    Segmentation fault
    

    This is one of the reasons why the strcpy function is discouraged, and usage of copy and concatenate functions that require specifying the sizes of the strings involved are recommended.

提交回复
热议问题