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?
Change
To
“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.