Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
zeromemory string state question
#3
(08-27-2018, 12:39 AM)Madammar Wrote: i do something like some times when i click on button 4 or 5 times i can see this text in memory viewer

Such code is VERY dangerous the way you have written it.  A String contains reference counted data, so if you have multiple String variables referencing the same physical data, you end up wiping out all of the variables together.  But more importantly, in your example, pstr is pointing at a string literal, so it has a reference count of -1, and you end up trying to zero out read-only memory!  In both cases, you need to call UniqueString() to ensure that pstr is the only variable referencing the data, and to ensure the data is writable:

Code:
procedure TForm1.OnClick(Sender: TObject);
var
 pstr: string;
begin
 pstr := 'abcdefghijklmnobqrsputwjdgdfkljfhghjfggffhgfj;
 UniqueString(pstr); // <-- add this!

 // I would use a type-cast instead of indexing...
 ZeroMemory(PChar(pstr), Length(pstr)*SizeOf(Char));
 // or: ZeroMemory(Pointer(pstr), Length(pstr)*SizeOf(Char));

 // Also, note the RTL has a ByteLength() function in the SysUtils unit...
 // ZeroMemory(..., ByteLength(pstr));

 pstr := '';
end;

(08-27-2018, 02:53 PM)kudzu Wrote: Which compiler? D2009+ is Unicode. Pre 2009 strings are Ansi.

Doesn't matter in this example, the code is using the generic String and Char types, so it would be calculating the correct byte length in all versions.

Reply


Messages In This Thread
zeromemory string state question - by Madammar - 08-27-2018, 12:39 AM
RE: zeromemory string state question - by kudzu - 08-27-2018, 02:53 PM
RE: zeromemory string state question - by rlebeau - 08-27-2018, 08:00 PM
RE: zeromemory string state question - by kudzu - 08-28-2018, 04:51 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)