tags:

views:

62

answers:

3

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

+1  A: 

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

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

etc.

Carl Norum
+1  A: 

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 M
+1  A: 

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.

Oli Charlesworth