Possible Duplicate:
How do you reverse a string in place in C or C++?
Why is this C code causing a segmentation fault?
Modifying value of char pointer in c produces segfault
Running a very simple code example
#include <stdlib.h>
#include <iostream>
char* last_char(char* s){
char* last = s;
while (*last) ++last;
return last;
}
char* in_place_reverse(char* s) {
char* left = s;
char* right = last_char(s);
char temp;
while( left < right ) {
temp = *left;
*left = *right;
*right = temp;
left++;
right--;
}
return s;
}
int main(){
char * s = "letters\n";
std::cout << in_place_reverse(s);
}
All the time I get
Segmentation fault
But from my point of view I’m not doing anything illegal within the code.
Please help me to determine what’s wrong.
P.S. I compile with
g++ example.c
Two problems:
char s[] = "letters\n"to make a mutable copy.last_char()in fact returns a pointer to the sentinel'\0'at the end of the string — it points beyond the last character. Changereturn lasttoreturn last - 1. Otherwise you are going to move the sentinel around too, and that’s almost certainly not what you want. (Note that this will return a pointer to garbage if the string is zero-length. You should fast-succeed inin_place_reverse()if*s == '\0'to avoid this complexity.)