Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a procedure like SetLength that also zeros the memory?

In some cases I need to set size of a dynamic array and then fill it with zeros.

Something like:

procedure SetLengthAndZero(VAR X; NewSize: Integer);
begin
   SetLength(x, newsize);
   if newsize > 0
   then FillChar(x[0], length(x)* SizeOf(x[0]), 0);
end;

But the code above (obviously) won't compile.


In Delphi 7, the content of the memory is undefined after SetLength.

like image 967
Server Overflow Avatar asked Oct 10 '16 14:10

Server Overflow


1 Answers

Read Embarcadero's documentation:

procedure SetLength(var S: <string or dynamic array>; NewLength: Integer);

For a dynamic array variable, SetLength reallocates the array referenced by S to the given length. Existing elements in the array are preserved and newly allocated space is set to 0 or nil.

This means that SetLength is all you want.


If you want to clear the whole dynamic array, not just allocate more items and preserve existing items, just call SetLengthwith NewLength = 0 before calling it again with the wanted length.

A generic solution:

Type
  TDynArrayTool = record
    class procedure ClearAndSetLength<T>( var arr : TArray<T>; newLen : Integer); static;
  end;

class procedure TDynArrayTool.ClearAndSetLength<T>(var arr: TArray<T>;
  newLen: Integer);
begin
  Setlength(arr,0);
  SetLength(arr,newLen);
end;
like image 195
LU RD Avatar answered Nov 15 '22 06:11

LU RD