Search code examples
csegmentation-faultbus-error

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


Why am I getting a bus error? The problematic line is marked inside the code.

Exercise 2-4. Write an alternative version of squeeze(s1,s2) that deletes each character in s1 that matches any character in the string s2.

    #include <stdio.h>

    /*
     * Detects if a char is inside a string
     */
    char in_string(char c, char s[]) {
        int i = 0;
        while (s[i] != '\0') {
            if (s[i++] == c)
                return 1;
        }
        return 0;
    }

    /*
     * Returns the string s without any chars that are in map
     */
    void squeeze(char s[], char map[]) {
        int i, j;

        for (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");
    }

Solution

  • Because "XALOMR" is a string literal (which is read-only) and you cannot modify it (as you do here: s[j++] = s[i];)

    A way around it is:

    main() {
        char s1[] = "XALOMR";
        char s2[] = "EWRTOG";
    
        squeeze(s1, "AO");
        squeeze(s2, "RGV");
    }
    

    Which will create an array of chars on the stack.