Possible Duplicate:
Why is this C code causing a segmentation fault?
I am writing a simple string reverse script.
I added print statements to debug. I keep getting a run time exception before Error1. But I can't seem to figure out the reason.
Here's my code:
#include <iostream>
#include <cstdlib>
using namespace std;
int strlen(char* s){
int i = 0;
while(*s != '\0'){
i++;
s++;
}
return i;
}
void reverse(char* src){
char* dest = src+strlen(src)-1;
char temp;
while(src < dest){
temp = *src;
cout << "Error0" << endl;
*src = *dest;
cout << "Error1" << endl;
*dest = temp;
cout << "Error2" << endl;
src++;
dest--;
}
}
int main (void){
char* s = "Hello world";
cout << s << endl;
int i = strlen(s);
cout << i << endl;
reverse(s);
cout << s << endl;
getchar();
return 0;
}
Here's my output:
Hello world
11
Error0