TStringLists use what is called sparse memory management. This means that memory (including the memory for the object's pointer) is assigned to each element only when something is placed in the string. Therefore, when an object is referenced without the string, no memory is allocated but it is trying to be accessed anyway, hence the AV.
There are a couple solutions: 1) use the AddObject method, 2) assign a value to the corresponding string first.
Note: Objects stored in TStrings descendants do not get freed when the TStrings object is destroyed. The lifetime of anything you place in here must be explicitly maintained.
procedure example1;
begin
with TStringList.Create do
try
Objects[0] := TObject.Create; { This will AV }
finally
Objects[0].Free;
Free;
end;
end;
procedure example2;
begin
with TStringList.Create do
try
AddObject('This is one good way.', TObject.Create);
Add('This is another good way.');
Objects[1] := TObject.Create;
finally
Objects[0].Free;
Objects[1].Free;
Free;
end;
end;
No comments:
Post a Comment
Comments are welcome but I do moderate them. This is simply to keep things wholesome for general family viewing. By default, comments will be accepted. The few things that will cause a comment to be rejected are:
1. It is too long even though it may be well-written and make interesting points. It's supposed to be a comment, not an essay. If you have that much to say, write a blog article and backlink to me.
2. It is nasty, impolite or uses language that is unacceptable.
3. It includes a a link that has a typo or is broken in some other way.
4. It should have been sent as an e-mail since it is clearly addressed to me and does not appear to have been intended for other readers.
5. It is blatantly self-promotional. This does not mean it can't be self-promotional at all, but it should add some value over an above the marketing.