0

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

Community
  • 1
  • 1
Mike
  • 413
  • 1
  • 3
  • 13

3 Answers3

2

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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1

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

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

etc.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
1

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;
}
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272