问题
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?
回答1:
Change
char * s = "sample text";
To
char s[] = "sample text";
"sample text" is a string literal which may reside in a read-only section of your address space. Using the array syntax ensures this string is copied to stack, which is writable.
回答2:
Your s
is pointing to a string literal:
char * s = "sample text";
In the function reverse
you are trying to modify the string literal which results in undefined behavior.
To fix this make s
a char array:
char s[] = "sample text";
来源:https://stackoverflow.com/questions/5220206/reverse-a-string-in-c-solution-segfaulting