This is a simple string reversal part of a bigger program.
char* strRev(char* exp)
{
char temp;
int n = strlen(exp);
for(int i = 0; i < n/2; i++)
{
temp = exp[i];
exp[i] = exp[n-i-1];
exp[n-i-1] = temp;
}
return exp;
}
int main()
{
printf("%s", strRev("Harshit"));
}
Putting this on a separate file and running GDB, the segmentation fault occurs at the line
exp[i] = exp[n-i-1];
Now I ran the same code using C++ and std::string
and the program ran correctly.
What is the problem in the code?
Edit: Here's the C++ code that I used.
std::string strRev(std::string exp)
{
char temp;
int n = exp.length();
for(int i = 0; i < n/2; i++)
{
temp = exp[i];
exp[i] = exp[n-i-1];
exp[n-i-1] = temp;
}
return exp;
}