Alex Rivera | Logout

Why is this string reversal C code causing a segmentation fault?

Asked 2009-10-23T17:01:29.123
30

I am trying to write code to reverse a string in place (I'm just trying to get better at C programming and pointer manipulation), but I cannot figure out why I am getting a segmentation fault:

#include <string.h>

void reverse(char *s);

int main() {
    char* s = "teststring";
    reverse(s);

    return 0;
}

void reverse(char *s) {
    int i, j;
    char temp;

    for (i=0,j = (strlen(s)-1); i < j; i++, j--) {
        temp = *(s+i);     //line 1
        *(s+i) = *(s+j);   //line 2
        *(s+j) = temp;     //line 3
    }
}

It's lines 2 and 3 that are causing the segmentation fault. I understand that there may be better ways to do this, but I am interested in finding out what specifically in my code is causing the segmentation fault.

Update: I have included the calling function as requested.

Edit
Report

1 Answer

-1

I think strlen can not work since s is not NULL terminated. So the behaviour of your for iteration is not the one you expect. Since the result of strlen will be superior than s length you will write in memory where you should not be.

In addition s points to a constant strings hold by a read only memory. You can not modify it. Try to init s by using the gets function as it is done in the strlen example

answered 2009-10-23T17:17:44.860

Your Answer