Segmentation fault (core dumped) in a simple C code

前端 未结 3 556
天涯浪人
天涯浪人 2021-01-20 04:37

I am new in C. I am referring to the book \"The C Programming Language\" by Brian W Kernighian and Dennis Ritchie. There is a code for pointer increment and assignment give

3条回答
  •  独厮守ぢ
    2021-01-20 05:07

    s and t are both string literals, and you can't modify a string literal. But this piece of code

    *s++ = *t++
    

    will modify s, which causes segmentation fault.

    To fix it, use a char array. I also modified the printf part to make it legal.

    #include
    
    int main()
    {
        char arr[] = "Goal";
        char *s = arr;
        char *t = "Home";
        while(*s++ = *t++) 
            ;
        printf("%s\n", arr);
        return 0;
    }
    

    However, I think this program is better done using an individual function to copy the string, the program will look clearer.

    #include
    void my_strcpy(char *s, char *t);
    
    int main()
    {
        char s[] = "Goal";
        char *t = "Home";
        my_strcpy(s, t);
        printf("%s\n", s);
        return 0;
    }
    
    void my_strcpy(char *s, char *t)
    {
        while(*s++ = *t++) 
            ;
    }
    

提交回复
热议问题