Forum > LCL
Access Violation with TStringList
spitofland:
I am running Lazarus-0.9.29-25159 and fpc-2.4.1-20100504 for Win 64-bit on a Windows 7 (64-bit) machine. I passed a TStringList object by reference to a function that I created. The function works perfectly, but inside the function I get an Access Violation if I try to run this code:
--- Code: ---function TImportForm.ParseStr(Line:String;Delim,Quote:Char;var Data:TStringList) : Boolean;
begin
Data.Clear; //Access violation
end;
--- End code ---
But I don't get any errors if I run:
--- Code: ---function TImportForm.ParseStr(Line:String;Delim,Quote:Char;var Data:TStringList) : Boolean;
begin
Data.Add('Test String');
Data.Add('Test String2');
Data.Add('Test String3');
end;
--- End code ---
Then, after using this function (without using the Clear function) I get an Access Violation when I call:
--- Code: --- ParseStr(CurrLine,ColumnChar,QuoteChar,Fields);
ShowMessage(Fields.Strings[1]);
--- End code ---
What would cause an Access Violation with Clear and Strings[1], but not with Add?
eny:
The AV is caused by passing a non-initialized object var.
I'd say that that needs fixing.
If you don't initialize the variable, it can contain anything and the results are unpredictable.
BTW: there is no reason to pass the object as a ref parameter.
Except when you really want to initialize it in your function, like so:
--- Code: ---function TImportForm.ParseStr(Line:String;Delim,Quote:Char;var Data:TStringList) : Boolean;
begin
Data := TStringList.Create;
Data.Add('Test String');
Data.Add('Test String2');
Data.Add('Test String3');
end;
--- End code ---
spitofland:
Oh, thanks. I guess I should have caught that.
When you say I don't have to pass it as a var, if I pass a TStringList as a normal parameter and make changes to it, will the changes persist?
eny:
--- Quote from: spitofland on May 26, 2010, 03:39:19 pm ---When you say I don't have to pass it as a var, if I pass a TStringList as a normal parameter and make changes to it, will the changes persist?
--- End quote ---
You mean pass it as a value parameter: yes!
As long as you initialize the objects before using them.
Like this:
--- Code: ---function TImportForm.ParseStr(Line:String; Delim, Quote:Char; Data:TStringList) : Boolean;
begin
Data.Add('Test String');
Data.Add('Test String2');
Data.Add('Test String3');
result := true // or false... or whatever value you need...
end;
.....
var MyList: TStringList;
begin
MyList := TStringList.Create;
if ParseStr('A String To Parse', ' ', '"', MyList) then ...
...
end;
--- End code ---
<<edit>> Forgot to remove the var keyword...
mas steindorff:
don't you need to use the var keyword in the funtion prameter list?
function TImportForm.ParseStr(Line:String; Delim, Quote:Char; var Data:TStringList) : Boolean;
or else you may be working on a copy of the varable/object
Navigation
[0] Message Index
[#] Next page