1

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?

1 Answer 1

5
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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.