0

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"));
  • 3
    First of all, `char *strCopy = (char *)str;` doesn't create a copy of the actual string, it just creates a copy of the *pointer* to the first character of the string. Secondly, literal strings are non-modifiable, any attempt to modify a literal string leads to *undefined behavior*. – Some programmer dude May 07 '22 at 14:42
  • 1
    And if you want to return a pointer to `char`, why do you set the return-type to `void *`? That you need to cast the returned pointer is a sign you're doing something wrong. – Some programmer dude May 07 '22 at 14:42
  • 2
    Lastly, when you run a program, all code in it has already passed the compiler, and it could be days, months or years between compilation and running. From source to running a program there are multiple steps: 1) Edit source; 2) Compile source into object files; 3) Link object files with libraries to create the executable program file; And 4) Run the executable program file. Your crash happens in step 4. – Some programmer dude May 07 '22 at 14:44
  • @Someprogrammerdude about the function and the return type. This is spelled out in the task: void *to_upper(const char *str), Returns a copy of string (str) converted to uppercase. In case of any error, return NULL Maybe I misunderstood something and am doing something wrong – The Dolaxom May 07 '22 at 14:54

1 Answers1

0

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.
fireshadow52
  • 6,298
  • 2
  • 30
  • 46