segmentation fault - C - K&R exercise 2.4 - why am I getting a bus error? -


why getting bus error? problematic line marked inside code.

exercise 2-4. write alternative version of squeeze(s1,s2) deletes each character in s1 matches character in string s2.

    #include <stdio.h>      /*      * detects if char inside string      */     char in_string(char c, char s[]) {         int = 0;         while (s[i] != '\0') {             if (s[i++] == c)                 return 1;         }         return 0;     }      /*      * returns string s without chars in map      */     void squeeze(char s[], char map[]) {         int i, j;          (i = j = 0; s[i] != '\0'; i++) {             if (! in_string(s[i], map)) {                 s[j++] = s[i]; // <--- bus error             }         }         s[j] = '\0';          printf("%s\n", s);     }      main() {         squeeze("xalomr", "ao");         squeeze("ewrtog", "rgv");     } 

because "xalomr" string literal (which read-only) , cannot modify (as here: s[j++] = s[i];)

a way around is:

main() {     char s1[] = "xalomr";     char s2[] = "ewrtog";      squeeze(s1, "ao");     squeeze(s2, "rgv"); } 

which create array of chars on stack.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -