Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
zeromemory string state question
#1
why some times when i do zeromemory for long string it does not get cleared from memory 

i do something like some times when i click on button 4 or 5 times i can see this text in memory viewer


Code:
procedure TForm1.OnClick(Sender: TObject);
var
 pstr: string;
begin
 pstr := 'abcdefghijklmnobqrsputwjdgdfkljfhghjfggffhgfj;

 ZeroMemory(@(pstr[1]), Length(pstr)*SizeOf(Char));

 pstr:='';

end;
Reply
#2
Which compiler? D2009+ is Unicode. Pre 2009 strings are Ansi.
Reply
#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
#4
thank you very much Remy for that effort and all of this data

kudzo i used delplhi berlin
Reply
#5
"Doesn't matter in this example"

But it helps to know in most cases what we are dealing with. Smile
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)