Why is this reverse string function giving a seg fault?
c, reverse, segmentation-fault, string
Solution
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.
Problem
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?