You need to overwrite the string with zeros when you are done with it. Like this:
ZeroMemory(Pointer(s), Length(s)*SizeOf(Char));
If you are paranoid that the compiler optimizes ZeroMemory, then you can use SecureZeroMemory. However, the Delphi compiler will not optimize far ZeroMemory so it is somewhat controversial.
If you just write:
s := '';
then the memory will be returned as well as the memory manager. Then you cannot control when, if ever, the memory manager reuses or returns memory.
Obviously, you will need to do this with all copies of the string, and therefore the only sensible approach is not to create copies of the confidential data.
None of this will help with the code according to your question, because your sensitive data is a string literal and therefore is stored in an executable file. This approach can only be applied to dynamic data. I believe your real program does not put sensitive data in literals.
Oh, and never pass the string to FreeAndNil. You can only pass object variables to FreeAndNil, but the untyped var parameter is used in this procedure, so the compiler cannot save you from your error.
source share