[Solved] C++ reverse string [closed]


The problem is

_aString=*&c;

which is a weird way of writing

_aString=c;

so that _aString is simply pointing to whatever the function argument was; this class doesn’t manage a the memory for a string (as std::string does), but refers to an external string managed elsewhere.

In your test case, that string is a string literal – which isn’t modifiable. So attempting to modify it, as reverse does, gives undefined behaviour; if you’re lucky, an access violation; if you’re unlucky, data corruption or some other unwanted runtime behaviour.

If your class is supposed to manage the memory, then it will need to allocate it in the constructor. Assuming this assignment is an exercise in memory management (otherwise, just use std::string), you’d want something like

_aString = new char[_lenght];
std::copy(c, c+_lenght, _aString);

and don’t forget the Rule of Three:

  • a destructor to release the memory with delete [] _aString
  • copy constructor, either deleted to prevent copying, or implemented to allocate a new buffer;
  • copy-assignment operator, either deleted to prevent copying, or implemented to copy into the existing buffer after resizing if necessary.

You might also consider fixing the spelling of _lenght to _length.

solved C++ reverse string [closed]