0

I have just started learning C from Ritchie and Kernighan's book. I am trying to reverse a string recursively, however, I get a segmentation fault with this code:

#include <stdio.h>
#include <string.h>
void reverse (char s[], int l, int r);

int main () {
 
    reverse("hello world", 0, 10);
}
void reverse (char s[], int l, int r) {

    
    int temp = s[l];
    s[l] = s[r];
    s[r] = temp;
    
    if (++l >= --r) {
        return;
    } else {
        reverse (s, ++l, --r);
    }
   
}

I'm not sure what im doing wrong, but I found that the segmentation fault occurs at s[l] = s[r];

1 Answers1

3

The string you're passing to the function is a string constant. They are immutable, and attempting to change them is undefined behavior which is why it's crashing.

Create a local array to store the string, then pass that in.

int main () {
    char str[] = "hello world";
    reverse(str, 0, 10);
}
dbush
  • 205,898
  • 23
  • 218
  • 273