开发者

changing a string value throws segmentation fault [duplicate]

开发者 https://www.devze.com 2023-01-12 14:17 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Why does simple C code receive segmentation fault?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Why does simple C code receive segmentation fault?

Hi,

check out the following code:

int main(int argc, char* argv[]){

    char* a = "z.x.f.t.e.a";
    char* b = ".";
    updateStr(a,b);
    return开发者_如何学编程 0;
 }
 int updateStr(char str[], const char* delim) {

     int i=0;
     int wordsCounter = 0;

    while (str[i] != '\0') {
        if (contains(delim,str[i])) {
            printf("CONTAINED %c\n",str[i]);  //debug
            str[i] = SEPERATOR;
            wordsCounter++;
        }
    i++;
    }
    //REST OF THE CODE....
return wordsCounter;
}

updateStr replaces each '.' with ';' (SEPERATOR). However, the line str[i] = SEPERATOR; throws segmentation fault and i don't have a clue why. what is the reason and how can i fix it?

thanks everyone


char *a = "blah"; declares a pointer to a string literal. These cannot be altered (well, the result is undefined). You may want to try char a[] = "blah"; instead, as this gives you a character array.


Don't try to modify string constants. Use an array instead.

char[] a = "z.x.f.t.e.a";

etc.


a is a pointer to a string literal (which you cannot modify). Change its definition.

int main(int argc, char* argv[]){
    char a[] = "z.x.f.t.e.a"; /* will be on the stack */
    char* b = ".";
    updateStr(a,b);
    return 0;
}
0

精彩评论

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

关注公众号