Reputation: 3
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;
}
Upvotes: 0
Views: 2080
Reputation: 229274
You're returning changed.c_str()
, which is just a pointer into the buffer managed by changed
. changed
is a local variable, and is destroyed when the function ends, so you're ending up returning a pointer to something that no longer exists.
Return the std::string changed
directly.
Upvotes: 3
Reputation: 837
you are returning a local variable allocated on stack.
basically your code translate to:
LPCSTR hasala(string original, char key){
string changed;
return changed.c_str();
}
either allocate the memory (caller must free it) or return a std::string
Upvotes: 1
Reputation: 147018
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
.
Upvotes: 3