3

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;
}
Harshit Joshi
  • 260
  • 4
  • 15
  • 3
    You’re passing a string literal which is most likely in a read-only segment. – Paul R Apr 12 '20 at 07:05
  • @PaulR Okay. That solved the problem. But why does my code run using ```std::string``` on C++? – Harshit Joshi Apr 12 '20 at 07:09
  • The code works on c++ because the constructor of std::string will copy the const char* string into rw memory. – everclear Apr 12 '20 at 07:22
  • Show that C++ code. `std::string` variables are mutable (unless declared `const`). – kaylum Apr 12 '20 at 07:22
  • @kaylum I guess there is no need to as I understood everclear 's comment. But still for other users, I edited the question. – Harshit Joshi Apr 12 '20 at 07:24
  • 1
    The short version is in C++ the *string-lteral* is used to initialize a `std::string` so the `std::string` is mutable thereafter. In C, the *string-literal* is contained in *read-only* memory (on all but a few outlier implementations). When you attempt to modify the string literal in C - BAM! (SegFault) – David C. Rankin Apr 12 '20 at 07:31

0 Answers0