Segmentation fault (core dumped) in a simple C code

倖福魔咒の 提交于 2020-01-11 09:58:07

问题


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 given in the book as follows.

#include<stdio.h>

int main()
    {
        char *s = "Goal";
        char *t = "Home";
        while(*s++ = *t++) printf(*s);
        return 0;
    }

The code is saved and compiled using the command

gcc ptr.c -o ptr -std=c99

Now on running the code by running command

./ptr

I get the following error

Segmentation fault (core dumped)

The error seems to be inside the while loop condition. But the code is exactly as given in the book. What am I missing?


回答1:


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<stdio.h>

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<stdio.h>
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++) 
        ;
}



回答2:


The problem is that printf expects the first parameter to be a char *, that is, something that points to a character, or the address of a character. When you say printf(*s) you're passing it an actual character, i.e. a number from 0 to 255 or -128 to 127, and the program is going to treat that number as an address, which isn't going to be a valid address on your system.




回答3:


When ever we say *s = "hello" , s is pointing to an address which is present in text segment("hello" goes into text segment). So obviously changing the value of text segment results in SEGV termination.

And for s[] = "hello" if we do *s++, we are incrementing (modifying) the base address so we got "lvalue required as increment operand" error.



来源:https://stackoverflow.com/questions/18928799/segmentation-fault-core-dumped-in-a-simple-c-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!