shiraz
shiraz

Reputation: 1218

Bus error in a simple C program

I am trying to reverse a C style string using the following simple program.

#include "stdio.h"
void reverse (char * str);
int main (int argc , char* argv[]){

    char *str = "hello";
    reverse(str);

return 0;

}

void reverse (char *str)
{
    char *end = str;
    char tmp;
    if(str){
            while(*end){
                    ++end;

            }
            --end;
            while(str < end){
                    tmp = *str;
                    *str++ = *end;
                    *end-- = tmp;

            }
    }
}

I can't figure out why I get a "bus error" when I try to run the above program. I am using i686-apple-darwin10-gcc-4.2.1. Thanks

Upvotes: 2

Views: 1104

Answers (2)

Jesus Ramos
Jesus Ramos

Reputation: 23266

String literals in C are stored in the .data section of the binary which is read only memory. When saving it as const char * or char * they are non modifiable (in some cases if you modify the access fails silently or in your case you get a bus error because it's ROM).

Try using char str[] = "hello"; instead (I believe this should work, but I may be wrong).

Upvotes: 4

AusCBloke
AusCBloke

Reputation: 18502

If you change char *str = "hello"; to char str[] = "hello"; your error will go away, since string literals are stored in a read-only part of memory and trying to modify "hello" may cause your program to crash (as it does in this case).

Declaring str as a char[] will copy the literal "hello" into a non-const buffer that you can modify the contents of.

Upvotes: 4

Related Questions