lMolly
lMolly

Reputation: 19

bus error:10 when try to reverse string in c

I am new to c and tried to write a simple str reverse function.

Here is my code I got online, compiled ok, but raise "bus error:10" when run.(please ignore so many printf, I was trying to figure out every step with them)

#include <stdlib.h>
#include <stdio.h>

char *str_reverse( char *begin, char *end ) {
    char *res;
    char temp;
    char temp2;
    res = begin;
    printf("str %s %s\n", begin,end);
    printf("res add %p begin add %p, end add %p\n", res, begin, end);
    while (end > begin) {
        printf("start\n");
        temp = *end;
        printf("temp %c\n",temp);
        *end = *begin;
        printf("end addr %p\n",end);
        end--;
        *begin = temp;
        printf("result %s\n", res);
        begin++;
    }
    printf("result %s\n", res);
    return res;
}

int main() {
    char *begin = "abc";
    char *end;
    end= begin + 2;
    char *new = str_reverse(begin, end);
    printf("value %s\n", new);
    return 0;
}

and the result is:

str abc c
res add 0x1082fdf86 begin add 0x1082fdf86, end add 0x1082fdf88
start
temp c
Bus error: 10

I guess the problem lies at "*end = *begin", but I don't know why? Can you help me? Thanks!

Upvotes: 1

Views: 267

Answers (1)

DrC
DrC

Reputation: 7698

You are trying to reverse a constant string. As a constant, it is stored in a segment that doesn't allow writing. Instead, allocate a writable buffer (array), copy your string in to it, and then apply your function.

int main() {
   char *str = "abc";
   char *begin = malloc(strlen(str)+1);
   if (!begin) {
       /* handle error*/
   }
   strcpy(begin, str);
   char *end;
   end= begin + 2;
   char *new = str_reverse(begin, end);
   printf("value %s\n", new);
   free(begin);
   return 0;
}

Upvotes: 2

Related Questions