Search code examples
c++stringfunctionlpcstr

The return value of a LPCSTR function becomes trashy


I was coding a simple XOR encryption program and then I noticed that the return value of a function is not the kind I expect to see.

I just can't find a problem in my code, could anyone help me?

Here's the program code:

#include "windows.h"
#include "iostream"

using namespace std;


LPCSTR hasala(string original, char key){

  string changed;

  for (int temp = 0; temp < original.size(); temp++){
  changed += original[temp] ^ (int(key) + temp) % 255;
  }

  cout << changed.c_str()<<"\n\n";//works, output "acagaca"

  LPCSTR adart = changed.c_str();

  cout << adart<<"\n\n";//works, output "acagaca"

  return adart;

}

int main(){

    cout << hasala("abcdefg", 0);//doesn't work, output "||||@ER|||"...

    cout << "\n\n";

    Sleep(8000);

    return 0;
}

Solution

  • The pointer that you have is to memory owned by the std::string on the stack - when the std::string goes out of scope, it frees it, and then you read it. You must return std::string, not LPCSTR.