Search code examples
cmemoryarguments

Error: Process finished with exit code 138 (interrupted by signal 10: SIGBUS)


I'm learning C programming and I wrote a function and wanted to see how it work. Here is the snippet:

#include <stdio.h>

void squeeze(char s[], int c) {
    int i, j;
    for (i = j = 0; s[i] != '\0'; i++) {
        if (s[i] != c)
            s[j++] = s[i];
    }
    s[j] = '\0';
    printf("Converted: %s", s);
}

int main() {
    squeeze("abcdefghigk", 'c');
}

But when I run it, I received this: Process finished with exit code 138 (interrupted by signal 10: SIGBUS)

I'm using macbook M1, OS13.4, Clion C23 standard.

Result expected: abdefghigk

But nothing showed up in the terminal, did I make mistakes when pass the arguments?

I have reviewed this issue, it looks similiar, but I'm not quite understand the answers, could someone please help explain?


Solution

  • It is undefined behavior to modify a string literal.

    From the C Standard (6.4.5 String literals)

    7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

    Use an array for the string:

    char input[] = "abcdefghigk";
    squeeze(input, 'c');