I am following an example of a book in writing a function to reverse a string in C.
This is the following problem. But when I execute it under ubuntu using gcc. I get a seg fault.
I have tried debugging it, but I don’t understand how can this line ‘*start++ = *end;’ causing a seg fault.
I appreciate someone can help me understand the seg fault.
#include <stdio.h>
#include <stdlib.h>
void myreverse(char* str) {
int len = strlen(str);
char tmp;
char* start = str;
char* end = str + (len -1);
while (start < end) {
tmp = *start;
// this is causing Segmentation fault
*start++ = *end;
*end-- = tmp;
}
}
int main(void) {
char* test = "Hello World";
puts(test);
myreverse(test);
puts(test);
return EXIT_SUCCESS;
}
when you dynamically give a string to a character pointer, the string you give gets saved in Read only part of data segment..Then you are passing this address to your myReverse function where you are trying to change the contents of that location in the line
which cause the segmentation fault..
Just change this line
to
and it wouldn’t crash..See this thread for more details..