I can't figure out what's wrong with my function - it causes a breakpoint on return.
std::string generateHash(std::string source)
{
CryptoPP::SHA1 hash;
byte digest[CryptoPP::SHA1::DIGESTSIZE];
hash.CalculateDigest(digest, (const byte*)source.c_str(), source.size());
std::string output;
CryptoPP::HexEncoder encoder;
CryptoPP::StringSink test = CryptoPP::StringSink(output);
encoder.Attach((CryptoPP::BufferedTransformation*)&CryptoPP::StringSink(output));
encoder.Put(digest, sizeof(digest));
encoder.MessageEnd();
return output; // here
}
encoder.Attach((CryptoPP::BufferedTransformation*)&CryptoPP::StringSink(output));
In this line, CryptoPP::StringSink(output)
is a temporary object. After this call CryptoPP::StringSink(output)
no longer exists. So If you try to follow its address (encoder.Attach
and encoder.Put
), you will get undefined behavior. (Like you should never return the address of a local variable)
My code for reference:
std::string generateHash(std::string source)
{
CryptoPP::SHA1 hash;
byte digest[CryptoPP::SHA1::DIGESTSIZE];
hash.CalculateDigest(digest, (const byte*)source.c_str(), source.size());
std::string output;
CryptoPP::HexEncoder encoder;
CryptoPP::StringSink test = CryptoPP::StringSink(output);
encoder.Attach(new CryptoPP::StringSink(output));
encoder.Put(digest, sizeof(digest));
encoder.MessageEnd();
return output;
}