Home > Mobile >  to_upper program does not compile due to bus error in C
to_upper program does not compile due to bus error in C

Time:05-08

I have a simple function that should convert lowercase characters to uppercase. But at a certain point, I get a bus error. What does this error mean and how can it be fixed?

PS I've been trying to figure out what this error means for a long time and as a result I can't figure out what the difference is between bus error and segmentation fault

void *to_upper(const char *str) {
    char *strCopy = (char *)str;

    int strLength = strlen(strCopy);

    for (int i = 0; i < strLength; i  ) {
        if (strCopy[i] >= 'a' && strCopy[i] <= 'z') {
            strCopy[i] = (int)strCopy[i] - 32; // ERROR -> zsh: bus error  ./a.out
        }
    }

    return strCopy;
}
printf("to_upper: %s", (char *)to_upper("TeSt"));

CodePudding user response:

See this question for an answer to "how does a bus error differ from a segmentation violation".

As to why you're getting a bus error in your case, you're effectively modifying a string literal, as Some programmer dude said in a comment on your OP. Here's why:

  1. You call your function with "TeSt" as an argument.
  2. The function parameter str gets assigned the location of the string literal "TeSt", which is located in in unmodifiable region of your program.
  3. You say char *strCopy = (char *) str, which is saying that strCopy should point to the same location as str. If you want to actually copy the string, use strdup(str) instead.
  4. When you say strCopy[i] = ..., because of the above, this is trying to change values in a memory region you don't have access to. That's why you get a bus error.
  •  Tags:  
  • c
  • Related