开发者

Why do I get a segmentation fault when I try to modify a string constant? [duplicate]

开发者 https://www.devze.com 2023-03-26 08:39 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: Why do I get a segmentation fault when writing to a string?
This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Why do I get a segmentation fault when writing to a string?

I expect the output of this program to be: ibjgsj开发者_StackOverflowfoet But i am getting a segmentation fault.

#include <stdio.h>
int main()
{

    char *p="haifriends",*p1;
    p1=p;
    while(*p!='\0')
    ++*p++;
    printf("%s   %s",p,p1);
    return 0;

}


I expect the output of this program to be: ibjgsjfoet

char *p="haifriends",*p1;

haifriends resides in read only section of the memory and cannot be modified. If you wish to modify the string literal then you have to make a copy.

char p[]="haifriends",*p1;
p1 = p;


Using two autoincrements in the same statement is asking for trouble. Don't try to be tricky. Write your code so that it is clear and expressive, and you'll get much better results.


You are trying to modify a string literal:

char *p="haifriends";
++*p;

Usually, string literals are allocated in non writable memory, hence the segfault.


The memory region in which p lies cannot be written to. You can only modify memory you've malloced or which lies on the stack:

#include <stdio.h>
int main()
{
    char buffer[11];
    char *p,*p1;

    strcpy(buffer, "haifriends");
    p = &buffer[0];

    p1=p;
    while(*p!='\0')
    ++*p++;
    printf("%s   %s",p,p1);
    return 0;
}

This is in no way good practice but I hope this example code clarifies the issue.


This will work:

#include <stdio.h>
int main()
{

    char p[11]="haifriends";
    char *p1;
    p1=p;
    while(*p1!='\0')
    ++*p1++;
    printf("%s   %s",p,p1);
    return 0;
}

Most compilers issue a warning on conversion from constant string to char*


Try changing *p="haifriends" to p[]="haifriends". Iirc you aren't allowed to modify string literals that are assigned to a regular character pointer, but you are when they're assigned to an array of characters.

Also ++*p++; is undefined behavior. Try *p++;p++;, or maybe ++*(p++); if that wouldn't also be undefined behavior (pretty sure it would be, though).

According to Michael, ++*p++; isn't undefined behavior, but I would still recommend going with *p++;p++; or ++*(p++); for clarification, as he agrees on that being a good idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消