开发者

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开发者_如何学C]; // <--- Bus Error
            }
        }
        s[j] = '\0';

        printf("%s\n", s);
    }

    main() {
        squeeze("XALOMR", "AO");
        squeeze("EWRTOG", "RGV");
    }


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.


When you try to change a string literal, you might get a fault.

What really happens is that the behavior of your code is undefined. If you're lucky, you'll get a fault. If you're unlucky, the code will appear to work as expected, which makes the error difficult to find.

Incidentally, you can declare a char array that gets its size from the string literal used to initialize it:

char var1[] = "XALOMR"; /* sizeof var1 == 7 */


Strings literals are read-only. When you try to change it, you get a fault.


You need to make these variables if you want to modify them.

char var1[20] =  "XALOMR";
squeeze(var1, "AO");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜