-2

I'm trying to reverse a string with the Reverse function. If I put size of the output array 10 and give 10 values as input , i give the perfect output. But if i initialize the size of output array with str.size() it gives some garbage value also.

#include<iostream>
#include<string>

using namespace std;

string Reverse(string str)
{
    cout<<str.size()<<endl;
    char output[str.size()];

    int temp = 0;
    for(int i = str.length()-1 ; i >= 0 ; i--)
    {
        output[temp] = str[i];
        temp++;
    }
    return output;
}

int main()
{
    char st[100];
    cout<<Reverse(gets(st));

    return 0;
}
Paul R
  • 208,748
  • 37
  • 389
  • 560

1 Answers1

1

There are a couple of issues here apart from the missing NULL terminator that others have already pointed out:

  • Use of a deprecated and dangerous function gets.

    The function provides no means to prevent buffer overflow of the destination array, given sufficiently long input string. std::gets was deprecated in C++11 and removed from C++14.

    std::fgets can be used instead.

  • Use of variable length array (which can be a compiler extension) in the Reverse function, a feature that is not supported by standard C++.

    char output[str.size()];

Since you are already using std::string in your program, you can use it for the output variable as well and that would fix your NULL termination issue.

And if you are not prevented from using standard library algorithms, you can use std::reverse instead of the Reverse function.

P.W
  • 26,289
  • 6
  • 39
  • 76
  • *"Use of variable length array"* why would OP use `std::string` **and** `char[]`? Using just the library string would fix this issue and the `NULL` terminating issue – Aykhan Hagverdili Apr 06 '19 at 08:02
  • Difficult for me to speculate on the intentions of the OP. I thought it would be good for him to know that VLA is not a standard feature. – P.W Apr 06 '19 at 08:04
  • I like your points, it's not my downvote, but I'd very much like to see a small in note, in the answer, regarding the use of `std::string` – Aykhan Hagverdili Apr 06 '19 at 08:06
  • 1
    @Ayxan: Added that. – P.W Apr 06 '19 at 08:13
  • Your last point is ill advice indeed. Why suggest a non-portable solution when you can call reverse on the string class, which you don’t even mention despite the fact that this answer is comprehensive in style? That’s why I downvoted. – Bathsheba Apr 06 '19 at 08:22
  • @Bathsheba: I did not suggest to use it. I mentioned that this was one of the issues with the code. I was telling the OP to fix these issues in the code. – P.W Apr 06 '19 at 08:25
  • By all means point out the bug. Then suggest using reverse; that’s the only credible fix. – Bathsheba Apr 06 '19 at 08:25
  • @P.W now it is perfect! – Aykhan Hagverdili Apr 06 '19 at 15:36