关于TList操作及释放的问题
大家都知道TList即可用于链表,又可用于数组,最近在做项目时遇到点小问题(可能是我对指针了解的不透彻吧),造成了不大不小的问题,下面就说说是怎么回事。
首先我先定义了Record及对应的指针类型。
PGoodsInfo = ^GoodsInfo;
GoodsInfo = record
ID : string;
Name : string;
Number : string;
end;
GoodsInfo = record
ID : string;
Name : string;
Number : string;
end;
下面是定义变量及添加数据
var
GoodsList : TList;
P:PGoodsInfo;
begin
GoodsList := TList.Create;
New(P);
P^.ID := '****';
P^.Name := '*****';
P^.Number := '*****';
GoodsList.Add(P);
end;
GoodsList : TList;
P:PGoodsInfo;
begin
GoodsList := TList.Create;
New(P);
P^.ID := '****';
P^.Name := '*****';
P^.Number := '*****';
GoodsList.Add(P);
end;
下面是错误的释放代码
var
i:Integer;
begin
for i := 0 to GoodsList.Count - 1 do
begin
Dispose(GoodsList.Items[i]); //这会造成内存泄漏
end;
GoodsList.Clear;
end;
i:Integer;
begin
for i := 0 to GoodsList.Count - 1 do
begin
Dispose(GoodsList.Items[i]); //这会造成内存泄漏
end;
GoodsList.Clear;
end;
正确的释放代码
var
i:Integer;
PGoods: PGoodsInfo;
begin
for i := 0 to GoodsList.Count - 1 do
begin
PGoods := GoodsList.Items[i];
Dispose(PGoods);
end;
GoodsList.Clear;
end;
i:Integer;
PGoods: PGoodsInfo;
begin
for i := 0 to GoodsList.Count - 1 do
begin
PGoods := GoodsList.Items[i];
Dispose(PGoods);
end;
GoodsList.Clear;
end;
我想正是因为程序不知道指针所对应的数据类型才会造成内存泄漏,指出就可以啦。望大家吸取教训。