1

I am trying to run the below code in Visual Studio 2008. But at run time the program is throwing an error

Unhandled exception at 0x002e1480 in reverseString.exe: 0xC0000005: Access violation writing location 0x002e573c.

void reverse(char *str)
{
    char *end = str;
    char tmp;
    if (str)
    {
      while (*end)
      {
         ++end;
      }
      --end;

      while (str < end) 
      {
        tmp = *str;
        *str++ = *end; // Error Here
        *end-- = tmp;
      }
   }
}

Thanks in advance for your great help.

3
  • 3
    How do you call reverse? how is str defined? maybe modifying string literal? otherwise it works fine: ideone.com/zC0Iip Commented Aug 25, 2013 at 3:53
  • 2
    It sounds plausible that the above function is called with a string literal which would fail! Commented Aug 25, 2013 at 4:02
  • @EdS. I think the OP is using C++, he just can't use std library. Commented Aug 25, 2013 at 4:17

6 Answers 6

2

It's trivial to reverse a string:

if (str) {
    std::reverse(str, str + strlen(str));
}

However, the precondition for this reversal to work is that str points to a writable string, i.e., it is declared as char* and is not initialized from a string literal! Although string literals can be used initialize char* objects, they do not necessarily point to writable memory (and on many contemporary system they do not point to writable memory).

In case you wonder how a naive implementation of std::reverse() could look like:

template <typename BiDirIt>
void reverse(BiDirIt begin, BiDirIt end) {
    for (; begin != end && begin != --end; ++begin) {
         swap(*begin, *end);
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Dietmar Kuhl, But I am trying to reverse the string without using any built-in methods..
std::reverse() isn't "built-in"! It is just a function template.
if (str) { // This line does not test if *str contains writable memory.
@user814064: that is correct. Nor is it common to test if the memory contains writable memory. It is one of the preconditions on calling this function.
Correct. But if the precondition is failing then that is the answer to why his program is failing.
1
std::reverse(str, str + std::char_traits<char>::length(str));

Note that reversing a string will result in broken text for many languages and encodings.

3 Comments

Just wondering, is there any advantage to using that over strlen? I'm completely inexperienced and unknowledgeable when it comes to std::char_traits.
@chris: Not really, I could've just said strrev. I just showed the "C++" way of doing it, without using any C functions. :)
Ah, I see. Well, I have to +1 for the note at the very least. I do recall seeing another SO question where at least one answer went into detail about that and fixed it.
1

Here is how to do it from scratch

#include <iostream>

void reverse(char* input)
{
    int size = strlen(input);
    int half = size / 2;

    for(int i = 0; i < half; ++i)
    {
        char temp = input[size - i - 1];
        input[size - i - 1] = input[i];
        input[i] = temp;
    }
}

int main()
{
    char word[] = "hello";
    reverse(word);
    std::cout << word;
}

Comments

0

I was able to use your reverse method with no issues, see below. The problem must be in how you're using the char* that you're passing in.

int main()
{
    char str[] = "Hello World!";

    reverse(str);

    cout << str << endl;

    return 0;
}

Here's the output

!dlroW olleH

1 Comment

you are right, I was passing the string directly to the function call.. Thanks a lot for your help
0

I think you are calling it like so

char* mystr = "Hello";
reverse(mystr);

right? But you can't do that since reverse is modifying the string (see here) which leads to the access violation. Call it as others have suggested by using

char mystr[] = "Hello";
reverse(mystr)

That being said using std::reverse as suggested by the others is a better solution.

Comments

0

Another approach, if you don't like/want iterator or reverse function.

 string revStr(string str){
        if (str.length() <= 1) {
            return str;
        }else{
            return revStr(str.substr(1,str.length()-1)) + str.at(0);
        }
    }

3 Comments

hmm... When Knuth made his famous comment about premature optimization, I don't think he had this kind of blatant disregard for the computer's time in mind.
It's not incorrect. It just makes so many extra allocations (dependent on the length of the string) for a process which can easily be done in place.
@BenjaminLindley yeah

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.