Can I copy a string in an empty string?

后端 未结 3 656
温柔的废话
温柔的废话 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:40

    You are writing past the memory space allocated to str on the stack. You need to make sure you have the correct amount of space for str. In the example you mentioned, you need space for a, b, and c plus a null character to end the string, so this code should work:

    char str[4];
    char *str2 = "abc";
    strcpy(str, str2);
    printf("%s", str);  // "abc"
    printf("%d", strlen(str));  // 3
    
    0 讨论(0)
  • 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 <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    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.

    0 讨论(0)
  • 2021-01-25 13:59

    It actually gives you undefined behavior, but your program doesn't have to fail because of that. That's how undefined behavior works.

    0 讨论(0)
提交回复
热议问题