0
    void reverse_String(char a[], int start, int length){
    int i;
    int j = length;
    for(i = start; i != j ; i++, j--){
        a[i] ^= a[j];
        a[j] ^= a[i];
        a[i] ^= a[j];
    }
    printf("%s", a);
   }

int main(int argc, char *argv[]){
    int length;
    char word[strlen(argv[1])];
    strcpy(word,argv[1]);
    length = strlen(word);
    reverse_String(word,0,length);
    return 0;
}

Why am I getting a Segmentation Fault for some entries, but it works for others? (Argv[1] is any String entered)

JGens
  • 11
  • 2
  • I suggest allocating `strlen(argv[1]) + 1` characters. Don't forget about the null terminator `'\0'` at the end. The null terminator is not counted by [`strlen()`](http://linux.die.net/man/3/strlen). – e0k Feb 19 '16 at 21:13
  • 1
    XOR is a neat trick, but less understandable, and no more efficient, than 3 operations involving a `temp` variable. – Weather Vane Feb 19 '16 at 21:14
  • 1
    This code seems to be taken from [here](http://stackoverflow.com/questions/8534274/is-the-strrev-function-not-available-in-linux). Note the similar complaints about using XOR swap there. XOR swap was invented a long time ago when memory was at much more of a premium. (The main benefit of it is that it saves the memory required for a temporary.) In this case, you can afford to spend one byte for clarity and efficiency. – e0k Feb 19 '16 at 21:15
  • 1
    Your reversal is going one character too far. You start `j` at length which, for `"hello"` is 5, however `a[5]` is _not_ `o`, it's the NULL termination. (Or, at least it would be if `word` was big enough... since you aren't leaving room in `word` for that termination you've got some undefined behavior going on.) – mah Feb 19 '16 at 21:18
  • @e0k ... especially when OP wastes memory duplicating function arguments as local variables. And I am sure the `main` code could be a one liner, even when `printf` is moved from the function to `main` (where it should be: separate ***form*** from ***functionality***). – Weather Vane Feb 19 '16 at 21:21

1 Answers1

4

If the number of characters is even, i will never be equal to j. You need to change your condition to i < j

Robert Jacobs
  • 3,266
  • 1
  • 20
  • 30