Question: I wrote this code to reverse strings. It works well, but when I enter short strings like "american beauty," it actually prints "ytuaeb nacirema2." This is my code. I would like to know what is wrong with my code that prints a random 2 at the end of the string. Thanks

```
// This program prompts the user to enter a string and displays it backwards.

#include <iostream>
#include <cstdlib>
using namespace std;

void printBackwards(char *strPtr); // Function prototype

int main() {
    const int SIZE = 50;
    char userString[SIZE];
    char *strPtr;
    cout << "Please enter a string (up to 49 characters)";
    cin.getline(userString, SIZE);
    printBackwards(userString);

}

//**************************************************************
// Definition of printBackwards. This function receives a      *
// pointer to character and inverts the order of the characters*
// within it.                                                  *
//**************************************************************

void printBackwards(char *strPtr) {
    const int SIZE = 50;
    int length = 0;
    char stringInverted[SIZE];
    int count = 0;
    char *strPtr1 = 0;
    int stringSize;
    int i = 0;
    int sum = 0;

    while (*strPtr != '\0') {
        strPtr++; // Set the pointer at the end of the string.
        sum++; // Add to sum.
    }
    strPtr--;

    // Save the contents of strPtr on stringInverted on inverted order
    while (count < sum) {
        stringInverted[count] = *strPtr;
        strPtr--;
        count++;
    }
    // Add '\0' at the end of stringSize
    stringInverted[count] == '\0';

    cout << stringInverted << endl;
}

```

Thanks.

Answer: 
Your null termination is wrong. You're using `==` instead of `=`. You need to change:

```
stringInverted[count] == '\0';

```

into

```
stringInverted[count] = '\0';

```
What is wrong with your code is that you do not even use strlen for counting the length of the string and you use fixed size strings (no malloc, or, gasp new[]), or the std::string (this is C++)! Even in plain C, not using strlen is always wrong because it is hand-optimized for the processor. What is worst, you have allocated the string to be returned (stringInverted) from the stack frame, which means when the function exits, the pointer is invalid and any time the code "works" is purely accidental.

To reverse a string on c++ you do this:

```
#include <iostream>
#include <string>

int main() {
    std::string s = "asdfasdf";
    std::string reversed (s.rbegin(), s.rend());
    std::cout << reversed << std::endl;
}

```

To reverse a string in C99 you do this:

```
char *reverse(const char *string) {
    int length = strlen(string);
    char *rv = (char*)malloc(length + 1);
    char *end = rv + length;
    *end-- = 0;
    for ( ; end >= rv; end --, string ++) {
        *end = *string;
    }
    return rv;
}

```

and remember to free the returned pointer after use. All other answers so far are blatantly wrong :)