How do we zero a AnsiString object? For example:
void TesteClass::test()
{
AnsiString cardNumber = "1234567890123456";
..
}
The AnsiString object is destroyed automatically, but its internal data is not cleaned, so a memory acquisition tool can read the information. We need to zero this data to avoid sensitive information be captured in memory.
The AnsiString class has the method c_str()
to access the internal data directly, but doing some like this is not recommended:
memset(cardNumber.c_str(), 0, cardNumber.Length());
What is the correct way to zero the AnsiString internal data before the object is destroyed?
There is nothing wrong with using
memset()
like you have shown. Usingc_str()
in this manner is correct (as long as you do not exceed theLength()
, sincec_str()
returns a pointer to const memory if theAnsiString
is blank):Since you are worried about information leakage, consider using
SecureZeroMemory()
instead ofmemset()
(see What’s the point of SecureZeroMemory?).To automate the zeroing (so you don't have to remember to do it), consider wrapping the
AnsiString
inside an RAII-styleclass
/struct
(you cannot derive fromAnsiString
directly, the RTL does not allow it), whose destructor performs the zeroing, and then use thatclass
/struct
where needed instead of usingAnsiString
directly.Just be careful, since
AnsiString
uses reference-counted data, so don't zero the data unless yourAnsiString
is the sole instance referencing the data: