Rohit Agrawal
Rohit Agrawal

Reputation: 161

Trying to reverse a string in place

I am trying to reverse a null terminated string in place in C++. I have written the code below:

//Implement a function to reverse a null terminated string

#include<iostream>
#include<cstdlib>

using namespace std;
void reverseString(char *str)
{
    int length=0;
    char *end = str;
    while(*end != '\0')
    {
        length++;
        end++;
    }
    cout<<"length : "<<length<<endl;
    end--;

    while(str < end)
    {

        char temp = *str;
        *str++ = *end;
        *end-- = temp; 


    }

}
int main(void)
{
    char *str = "hello world";
    reverseString(str);
    cout<<"Reversed string : "<<str<<endl;
}

However, when I run this C++ program , I get a a write access violation inside the while loop at the statement : *str = *end ;

Even though this is fairly simple, I can't seem to figure out the exact reason I am getting this error.

Could you please help me identify the error?

Upvotes: 1

Views: 4527

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258698

char *str = "hello world";

is a pointer to a string literal, and can't be modified. String literals reside in read-only memory and attempting to modify them results in undefined behavior. In your case, a crash.

Since this is clearly an assignment, I won't suggest using std::string instead, since it's good to learn these things. Use:

char str[] = "hello world";

and it should work. In this case, str would be an automatic-storage (stack) variable.

Upvotes: 5

Related Questions