首页  编辑  

记录中的String的内存释放

Tags: /超级猛料/Language.Object Pascal/指针、内存相关/   Date Created:
记录中的String,如果记录使用了指针的话,必须手动释放String的内存,否则内存使用的显示在资源管理器中不正确,内存会有泄漏!
测试代码如下:
Dispose(); //会判断指针的类型对应释放~~
Dispose(FList[i]); //将当成Pointer释放~~
Dispose(PMyRec(FList[i])); //将当成PMyRec释放~~

type
 TMyRec = packed record
   No : integer;
   Time: TDateTime;
   Value: string;
 end;
 PMyRec = ^TMyRec;
 TMyRecArray = array[0..0] of TMyRec;
 PMyRecArray = ^TMyRecArray;

var
 MyRecArray : PMyRecArray;

procedure TForm1.Button1Click(Sender: TObject);
var
 i: integer;
 R : PMyRec;
begin
 for i:= 1 to 1024 * 10 do
 begin
   New(R);
   R.No := i;
   R.Time := Now;
   R.Value := GetRandomString(Random(10 * 1024));
   FList.Add(R);
 end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
 FList := TList.Create;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
 FList.Free;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
 i: integer;
begin
 for i:= 0 to Pred(FList.Count) do
 begin
   Dispose(FList[i]);
 end;
 FList.Clear;
end;

procedure TForm1.Button3Click(Sender: TObject);
var
 i: integer;
begin
 for i:= 0 to Pred(FList.Count) do
 begin
   Dispose(PMyRec(FList[i]));
 end;
 FList.Clear;
end;