0

I am trying to reverse a string, No idea why am I getting this below error as Unhandled exception at 0x00f818c2 in CPP_TEST.exe: 0xC0000005: Access violation writing location 0x00f87838.? Please help me.

void swap(char* in, int start, int end)
{
    char *temp = new char;
    *temp = in[start];
    in[start] = in[end];//Unhandled exception at 0x00f818c2 in CPP_TEST.exe: 0xC0000005: Access violation writing location 0x00f87838.
    in[end] = *temp;
}
void Reverse(char* in, int start, int end)
{
    if(start == end)
    {
        cout << in <<endl;
        return;
    }
    else
    {
        while(start != end)
        {
            swap(in, start++, end--);
            //Reverse(in, start, end);
        }
    }
}
int main()
{


    char* in = "Hello";
    Reverse(in, 0, 4);
    system("pause");
    return 0;
}
Rasmi Ranjan Nayak
  • 11,510
  • 29
  • 82
  • 122
  • 4
    `in` points to a string literal. You cannot modify it. Plus, you have a memory leak in `swap`. – juanchopanza Jul 21 '14 at 15:58
  • 1
    Normally, one would use at least `std::swap`, if not `std::reverse`. Neither have these bugs. Anyway, a `char *` pointing to a string literal is deprecated in C++ (you should get a compiler warning, so turn them on/up if you don't) and illegal in C++11. – chris Jul 21 '14 at 16:05

1 Answers1

5

A string literal is not modifiable, and yet you are attempting to modify it. Use a modifiable string:

char in[] = "Hello";

In swap, you leak memory. You don't need to dynamically allocate memory there. The code can be

void swap(char* in, int start, int end)
{
    char temp = in[start];
    in[start] = in[end];
    in[end] = temp;
}

while(start != end)
{
    swap(in, start++, end--);
    //Reverse(in, start, end);
}

If end - start is an odd number, this loop will never terminate.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490