3

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?

madth3
  • 7,275
  • 12
  • 50
  • 74

4 Answers4

6

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
3

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.

Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
1

How are you calling the function? In other words, are you sure that the character array you're passing in is writable?

If the memory is okay, it probably crashes when you use != since there's no guarantee that that happens when you expect it to.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

if strlen(s) - 1 is odd then your condition i!=j will always be true.

nav_jan
  • 2,473
  • 4
  • 24
  • 42