1

I'm having Bus error: 10 when I call the same function twice or more times. For example, I've a function to change a word to lowercase, and if I call it more than one time, it gives me the bus error.

while(bla != NULL){
        if(bla->id != NULL && bla->type != NULL && bla->second_type != NULL){
            char * id_print = strtolower(bla->id);
            //char * type_print = strtolower(bla->type);
            //char * second_type_print = strtolower(bla->second_type);
            printf("%s\t_%s_\t%s\n", id_print, bla->type, bla->second_type);
        }
        else if(bla->id != NULL && bla->type != NULL){
            char * id_print = strtolower(bla->id);
            //char * type_print = strtolower(bla->type);
            printf("%s\t_%s_\n", id_print, bla->type);
        }
        bla = bla->next_symbol_entry;
    }

If I have the function call on comment, I don't have the error. But:

while(bla != NULL){
        if(bla->id != NULL && bla->type != NULL && bla->second_type != NULL){
            char * id_print = strtolower(bla->id);
            char * type_print = strtolower(bla->type);
            char * second_type_print = strtolower(bla->second_type);
            printf("%s\t_%s_\t%s\n", id_print, type_print, second_type_print);
        }
        else if(bla->id != NULL && bla->type != NULL){
            char * id_print = strtolower(bla->id);
            char * type_print = strtolower(bla->type);
            printf("%s\t_%s_\n", id_print, type_print);
        }
        bla = bla->next_symbol_entry;
    }

if I uncomment the function calls, this gives me the Bus error.

Can you help me to understand why?

The strtolower function is:

char * strtolower(char * str){

char * string = str;

if(str){
    for(; *str; ++str)
        *str = tolower(*str);
}

return string;

}
  • 1
    Several possible causes: your strings are not mutable (constant strings), your objects aren't properly allocated (destroyed temporaries?), or you haven't shown us something pertinent. – nneonneo May 02 '15 at 18:41
  • The argument for `tolower()` is `int`. You are sending a `char` type, which will be promoted to `int`. If the `char` is `signed` and negative, that will cause undefined behaviour in `tolower()`. The answer to this question http://stackoverflow.com/questions/17452847/why-putchar-toupper-tolower-etc-take-a-int-instead-of-a-char quotes *"...the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined."* – Weather Vane May 02 '15 at 19:07

0 Answers0