Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

pointers - Pre increment operator and dereference operator resulting in segmentation fault, can't seem to understand why

Found the following piece of code given in a test which asked to figure out the output.

#include <stdio.h>

int gate(char *P)
{
    char *q = P;
    q++;
    *q++;
    ++*q;
    return(q-P);
}


int main()
{
    char *s = "gateexam";
    int x = gate(s);
    printf("%d",x);
}

Ran it on an online compiler, but for some reason it is causing a segmentation fault because of the line "++*q" (commenting out this line makes the program run fine).

Can't understand what is causing this

screenshot of code and output

question from:https://stackoverflow.com/questions/65866685/pre-increment-operator-and-dereference-operator-resulting-in-segmentation-fault

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Can't understand what is causing this

A bug in the code is causing this. This program attempts to modify a string literal, which is prohibited by the language rules.

You can fix it like so:

int main()
{
    char s[] = "gateexam";
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...