简体   繁体   中英

C pointer ,seg fault

I have the following program going to segfault. I am unable to understand why. Kindly help me.

int main(){
    char *a="String One", *b="String Two";
    while(*a++=*b++);
return 0;
}

To analyse it, I removed the while loop and made it simpler. Still it gives segfault!

int main(){
    char *a="String One", *b="String Two";
    *a++=*b++;
return 0;
}

But this works. I mean no segfault!

int main(){
    char *a="String One", *b="String Two";
    *a++;
    *b++;
return 0;
}

Replying to Luchien:

I was actually trying to emulate strcpy. Something like this. Now that i know that string literal is read only, I could get this working. Thank you all.

main(){
char x[10];
char *xx = x;

char *y = "Hello";

char *t=x, *f=y;

while(*xx++ = *y++);

printf(" %s ...%s \n",t,f);
}

With

char *a="String One", *b="String Two";

your a points to readonly memory containing the given string. Modifying this is undefined behaviour.

Many operating systems store literal string values in a read-only memory section, which means that attempts to modify the memory lead to the OS telling the program: hey, you can't touch that! On unix systems the OS does this by sending the process the SEGV signal, which usually leads to process termination.

Since C programs run on bare metal embedded systems and on many different operating systems, some of which have this restriction, some of which don't, the C standard declares this undefined behaviour .

You're modifying a string literal, which is undefined behavior .

I also find it annoying that

char *a="String One"

is actually

const char *a="String One"

"StringOne" is stored in read-only memory, and can thus not be modified.

When you create a string constant by saying char *a="String One" 'a' is not an array, but a pointer which is initialized to point to a string constant. If you want to change the string that it points to, you can point it elsewhere, but trying to modify the contents in place results in undefined behavior.

在第三段代码中, *a++将访问由a指向的地址,该地址包含字符'S' ,因此没有段错误。

while(*xx++ = *y++);

Is this really something you want? What do you wish to accomplish? This is actually undefined behavior, as you don't know what xx will be after this. Will you first increment xx, or will you first copy the value from y to xx, and then increment? See http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf 6.5.2

Those strings that a, b are stored in data section. That section is read-only area. So you couldn't modify the strings at data section. a and b is just a pointer to point strings at data section. x is stored in stack, so you can modify it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM