Udit Gupta
Udit Gupta

Reputation: 3272

simple C code giving segmentation fault on gcc

I found a question somewhere ... here it is and its answer with explanation.

main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s   %s",p,p1);
}

 Answer:
 ibj!gsjfoet

 Explanation:
++*p++ will be parse in the given order

*p that is value at the location currently pointed by p will be taken

++*p the retrieved value will be incremented

when ; is encountered the location will be incremented that is p++ will be executed

Hence, in the while loop initial value pointed by p is ‘h’, which is changed to ‘i’ by executing ++*p and pointer moves to point, ‘a’ which is similarly changed to ‘b’ and so on. Similarly blank space is converted to ‘!’. Thus, we obtain value in p becomes “ibj!gsjfoet” and since p reaches ‘\0’ and p1 points to p thus p1 doesnot print anything.

I found something wrong with explanation on p1.I think p1 should print "hai friends" and output of p is fine as given.

but when I tried to run the same code on gcc compiler,its giving segmentatiion fault

here is the exact code which I tried to run ..

 #include<stdio.h>
 int main()
 {
 char *p="hai friends",*p1;
 p1=p;
 while(*p !='\0') ++*p++;
 printf("%s   %s",p,p1);
 return 0;
 }

If possible edit the title ,I could not find a suitable title which would explain the situation more clearly.

EDIT :

I tried to run the modified code as suggested by Mysticial ,But what I think output should be -

ibj!gsjfoet    hai friends

because I am incrementing only p0 but p1 should be as its initial place i.e. at the starting address of string.Please if anyone could explain it where I am getting it wrong ???

Upvotes: 1

Views: 783

Answers (2)

Mysticial
Mysticial

Reputation: 471249

Well for one, code like this: ++*p++ should be avoided because it's generally hard to read.

Secondly, the problem is that you are modifying a string literal. That's undefined behavior. Don't do it.

Instead, change your declaration to this:

char p[] = "hai friends";
char *p1;

and modify you code as such:

int main()
{

    char p[] = "hai friends";
    char *p0,*p1;
    p0 = p;
    p1 = p;
    while(*p0 !='\0') ++*p0++;
    printf("%s   %s",p0,p1);
    return 0;

}

Upvotes: 4

Michael Burr
Michael Burr

Reputation: 340218

"hai friends" is a literal string that can't be modified.

Upvotes: 1

Related Questions