0

Possible Duplicate:
Why is this C code causing a segmentation fault?

My code:

    void strrev(char *str) {
  char temp, *end_ptr;

  /* If str is NULL or empty, do nothing */
  if( str == NULL || !(*str) )
    return;

  end_ptr = str + strlen(str) - 1;

  /* Swap the chars */
  while( end_ptr > str ) {
    temp = *str;
    *str = *end_ptr;
    *end_ptr = temp;
    str++;
    end_ptr--;
  }
}
void main() {
    char temp;
    char* x = "Hel2313lo123";
    //temp = *x;
//  strReverse(x);
    strrev(x);
    printf("\n%s", x);
}

And the function strrev() is in fact, copied straight from: How do you reverse a string in place in C or C++?

I get a segmentation fault whenever I try to run this. Why would that be happening?

THank you!

Community
  • 1
  • 1
pritamps
  • 121
  • 10
  • 5
    Change `char *x` to `char x[]`, then read [this question and answers.](http://stackoverflow.com/questions/1614723/why-is-this-c-code-causing-a-segmentation-fault) – WhozCraig Jan 06 '13 at 18:27

1 Answers1

2

char* x = "Hel2313lo123"; means read-only C-string. You need array char x[] = "Hel2313lo123";

fasked
  • 3,555
  • 1
  • 19
  • 36
  • 2
    Allthough the fix is correct, the explanation is quiet vague and also inaccurate ... – alk Jan 06 '13 at 18:30
  • 1
    @alk I think it's enough considering OP's level. But yes, it is more than inaccurate. – fasked Jan 06 '13 at 18:34