Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this reverse string function giving a seg fault?

I want to make a reverse string function and I have done it like this:

void reverse_str(char s[])  {
    int i, j;
    char ch;
    for(i = 0, j = strlen(s) - 1; i < j; i++, j--)  {
        ch = s[i];
        s[i] = s[j];
        s[j] = ch;
    }
    return ;
}

But for some reason when I change i < j to i != j I get a segmentation fault. This also happens when i and j are pointers. Why?


2 Answers

It's almost certainly because i and j pass each other (whether they're indexes or pointers is irrelevant here). For example, any string with an even number of characters will have this problem.

Consider the following sequence for the string drum:

     0123 <- indexes
     ----
s = "drum", i = 0, j =  3, swap d and m.
s = "mrud", i = 1, j =  2, swap r and u.
s = "murd", i = 2, j =  1, swap u and r, oops, we've passed each other.
s = "mrud", i = 3, j =  0, swap m and d.
s = "drum", i = 4, j = -1, swap who knows what, undefined behaviour.

Note that for a string with an odd length, you won't have this problem since i eventually equals j (at the middle character).

The i < j check also fixes this problem since it detects both equality of pointers and the pointers passing each other.

like image 91
paxdiablo Avatar answered Jan 28 '26 08:01

paxdiablo


If j starts as odd (when s has an even number of characters), then i and j will never be equal - so the loop will continue outside the bounds of the array s.

For example, if i = 0 and j = 1 when first evaluated, then the next loop will have i = 1 and j = 0 (note still not equal) and the third loop will have i = 2 and j = -1, hence the error.

like image 29
Rich O'Kelly Avatar answered Jan 28 '26 08:01

Rich O'Kelly