0

I am trying to reverse string using pointer (ref source). in function

string_reverse

Bus Error happened at this line when copying character from char pointer end to start char pointer :

 *start = *end;

I tried LLDB in VS code. Screen shot attached.

Can some one explain why there is bus error happened at below line?

*start = *end

Full code below:


#include <stdio.h>
#include <string.h>


void string_reverse(char* str)
{
    int len = strlen(str);
    char temp;
    char *end = str;
    char *start = str;

    /* Move end pointer to the last character */
    for (int j = 0; j < len-1; j++)
    {
        end++;
    }

    for(int i = 0; i< len/2;i++ )
    {
        temp = *start;
        *start = *end;
        *end = temp;

        /* update pointer positions */
        start++;
        end--;
    }
    
}


int main( void ) 
{

    char *str = "test string";
    
    printf("Original string is %s\n", str);
    string_reverse(str);
    printf("Reverse string is %s\n", str);
    return 0;
}

Actual result: Bus Error happened at line

*start = *end;

Expected output:

Reverse string is gnirts tset
user8811698
  • 118
  • 1
  • 7
  • 1
    Try `char *str = "test string";` --> `char str[] = "test string";` as attempting to reverse a _string literal_ is undefined behavior. – chux - Reinstate Monica Dec 09 '22 at 04:28
  • Thanks @chux - Reinstate Monica. It has worked. I got expected output. But I am still not clear why undefined behavior of char pointer initialized to string literals – user8811698 Dec 09 '22 at 04:33
  • 2
    Your code attempted to modify a _string literal_, no? That is UB since [C89 and K&R](https://stackoverflow.com/q/10001202/2410359). – chux - Reinstate Monica Dec 09 '22 at 04:38

1 Answers1

0

The error happens because

char * str = "...";

mean you have a pointer to a string literal. It's a constant string that you can not modify. When you change it to

char str[] = "...";

as chux-reinstate-monica mentioned, str will be char array with the length of your string, and you can modify it without any error.

A. Hajian
  • 104
  • 1
  • 4