Переверните строку в segfaulting решения C

I've come up with the following solution in C for reversing a string:

#include <stdio.h>

void reverse(char * head);

void main() {

  char * s = "sample text";
  reverse(s);
  printf("%s", s);
}

void reverse(char * head) {

  char * end = head;
  char tmp;

  if (!head || !(*head)) return;

  while(*end) ++end;

  --end;

  while (head < end) {
    tmp = *head;
    *head++ = *end;
    *end-- = tmp;
  }
}

However my solution is segfaulting. According to GDB, the offending line is the following:

*head++ = *end;

The line segfaults on the first iteration of the while loop. end points to the last character of the string "t" and head points to the beginning of the string. So why isn't this working?

5
задан codaddict 13 May 2012 в 08:42
поделиться