6

Possible Duplicate:
Why do I get a segmentation fault when writing to a string?

I want to write a simple C++ function that reverses a string/char[] by only pointer arithmetic. I understand the concept and have code already typed up.

I have the following .cpp file:

#include <iostream>
using std::cout;
using std::endl;

void reverse(char* target) //Requirements specify to have this argument
{
    cout << "Before :" << target << endl; // Print out the word to be reversed
    if(strlen(target) > 1) // Check incase no word or 1 letter word is placed
    {
        char* firstChar = &target[0]; // First Char of char array
        char* lastChar = &target[strlen(target) - 1]; //Last Char of char array
        char temp; // Temp char to swap
        while(firstChar < lastChar) // File the first char position is below the last char position
        {
            temp = *firstChar; // Temp gets the firstChar
            *firstChar = *lastChar; // firstChar now gets lastChar
            *lastChar = temp; // lastChar now gets temp (firstChar)
            firstChar++; // Move position of firstChar up one
            lastChar--; // Move position of lastChar down one and repeat loop
        }
    }
    cout << "After :" << target << endl; // Print out end result.
}

void main()
{
    reverse("Test"); //Expect output to be 'tseT'
}

I've stepped through in the debugger several times but each time it crashes around the temp = *firstChar line in the while loop. It freezes up here and causes the program to stop running and unable to finish. Is there something I am simply overlooking or is there something deeper as to why I can't do it this way.

EDIT: There is an else condition, but I removed it for the sake of brevity. It was after the if statement and it just prompted that the word was 1 char or no word was put.

Community
  • 1
  • 1
DrTran
  • 97
  • 2
  • 12

2 Answers2

8

The problem is not in the reverse function, but in the calling code.

reverse("Test");

String literals are read-only, attempting to modify one leads to undefined behavior. Pay attention to compiler warnings (or turn the warning level up if you aren't getting any). The line above should be generating warnings about a deprecated conversion from const char * to char * being performed.

To fix the code:

int main() // <-- note the return type, int NOT void!
{
  char str[] = "Test";
  reverse( str );
}
Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • Won me for the blink of an eye! +1 – higuaro Oct 22 '12 at 00:12
  • You sir were correct. This simple change was the fix. That was the problem that I wasn't getting the warning. As I believe my warning and error notices are set at the default. I guess I learned something extra besides pointer arithmetic today. Thanks again. – DrTran Oct 22 '12 at 00:15
0

This code will reverse it twice. Divide the loop by two.

pbies
  • 666
  • 11
  • 28