TStringList is not passing value - delphi

So i have a procedure, that is getting the list of dom nodes.
procedure TmainForm.getNodeListByClass(className:string; outputList:TStringList);
var
foundNode:TDomTreeNode;
foundNodesList:TStringlist;
begin
foundNodesList:=Tstringlist.Create;
foundNode:=nodeFindNodeByClassName(DomTree.RootNode,className);
if Assigned(foundNode) then
getNodeList(foundNode,foundNodesList);
outputList:=foundNodesList;
freeandnil(foundNodesList);
end;
And a procedure that is using it
procedure TmainForm.getByXpathBtnClick(Sender: TObject);
var
temp:TStringlist;
begin
temp:=TStringlist.Create;
temp.Add('testval');
getNodeListByClass('table_input',temp);
memo1.Lines:=temp;
getNodeListByClass('left iteminfo',temp);
dbgForm.memo1.Lines:=temp;
getNodeListByClass('left',temp);
dbgForm.memo2.Lines:=temp;
freeandnil(temp);
end;
And i really don't understand, why it wouldn't work, result of first procedure is always empty.
I found out, that when the first procedure is executing, "foundNodesList" have the correct list, and setting it to "outputList" is working too, but as soon as its returning to the second procedure (in "temp" list) its just empty.
So its clearing old data from "test" ('testval' what i am writing in the beginning), but not adding the result from the first one.
Could someone point me in the right direction?

The problem is here
outputList := foundNodesList;
FreeAndNil(foundNodesList);
The assignment is a reference assignment. I think that you are expecting the content of foundNodesList to be transferred into outputList. But what happens is that you end up with two variables referring to the same instance.
Your code can be fixed very easily. You do not need a temporary string list, you can simply populate the string list passed into the method.
procedure TmainForm.getNodeListByClass(className: string; outputList: TStringList);
var
foundNode: TDomTreeNode;
begin
outputList.Clear;
foundNode := nodeFindNodeByClassName(DomTree.RootNode, className);
if Assigned(foundNode) then
getNodeList(foundNode, outputList);
end;
Note that in the other function when you write
memo1.Lines := temp;
this works a little differently. The Lines property of a TMemo has a property setter that copies the right hand side, rather than taking a reference. Your code that performs assignment to Lines is therefore correct.

You must understand that objects are reference types in Delphi, and that these references are passed by value. So your procedure
procedure TmainForm.getNodeListByClass(className:string; outputList:TStringList);
var
foundNode:TDomTreeNode;
foundNodesList:TStringlist;
begin
foundNodesList:=Tstringlist.Create;
foundNode:=nodeFindNodeByClassName(DomTree.RootNode,className);
if Assigned(foundNode) then
getNodeList(foundNode,foundNodesList);
outputList:=foundNodesList;
freeandnil(foundNodesList);
end;
will never change the outputList of the caller. Indeed, the line
outputList:=foundNodesList;
merely sets the getNodeListByClass procedure's own local variable outputList, which was only a copy of the pointer to the caller's string list. Hence, this copy of the pointer is changed, but the actual object, and the caller's pointer to it, are left unchanged.
Also, even if this had not been the case, your code would have had a bug, because
freeandnil(foundNodesList);
destroys the string list object foundNodesList, and this is the same object that outputList points to at that point. Hence, if the caller would have been able to see the "new" outputList (if it had been a var parameter), it would only see a dangling pointer (memory corruption bug).
What you need is
procedure TmainForm.getNodeListByClass(const className: string; outputList: TStringList);
var
foundNode: TDomTreeNode;
foundNodesList: TStringlist;
begin
foundNodesList := TStringList.Create;
try
foundNode := nodeFindNodeByClassName(DomTree.RootNode, className);
if Assigned(foundNode) then
getNodeList(foundNode, foundNodesList);
outputList.Assign(foundNodeList);
finally
foundNodeList.Free;
end;
end;
assuming your functions do what I think they do. But this can be simplified to
procedure TmainForm.getNodeListByClass(const className: string; outputList: TStringList);
var
foundNode: TDomTreeNode;
begin
outputList.Clear;
foundNode := nodeFindNodeByClassName(DomTree.RootNode, className);
if Assigned(foundNode) then
getNodeList(foundNode, outputList);
end;
(I don't know if you want to append the list or replace it. You have to adjust the code accordingly.)
Also, notice that you always must protect your objects, using try..finally blocks, for instance. Your code must never leak resources (memory, for instance), not even if an exception is raised!

Related

E2555 Cannot capture symbol 'Self'

When I run the following code I get E2555 Cannot capture symbol 'Self'.
type
TLookupTable = record
FData: TArray<TOtherRec>;
procedure ReverseLeftToRight;
end;
procedure TLookupTable.ReverseLeftToRight;
begin
Parallel.For(0, Length(FData)-1).NoWait.Execute(procedure(i: integer) begin
FData[i]:= FData[i].ReverseLeftRight;
end); {for i}
end;
How do I fix this?
The problem is that var parameters (including hidden var parameters to Self) do not get captured. However, we do not want to copy the record, that would be useless, because then our method would not work.
The trick is to make the hidden self parameter explicit.
If it's a class, then it's easy (var S:= Self), if not you'll have to declare a pointer to your record.
procedure TLookupTable.ReverseLeftToRight;
type
PLookupTable = ^TLookupTable;
var
S: PLookupTable;
begin
S:= #Self;
Parallel.For(0, Length(FData)-1).NoWait.Execute(procedure(i: integer) begin
S.FData[i]:= S.FData[i].ReverseLeftRight;
end); {for i}
end;
Now the compiler no longer complains.
(Note that I'm using the implicit syntax for S^.xyz).
Delphi Rio
Using a inline var declaration as shown below, does not work.
//S: PLookupTable;
begin
var S:= #Self; //inline declaration
Parallel.For(0, Length(FData)-1).NoWait.Execute(procedure(i: integer) begin
S.FData[i]:= S.FData[i].ReverseLeftRight;
end); {for i}
This generates: E2018 Record, object or class type required.
I guess the inline #Self gets resolved to a generic pointer, which is a shame, because there is enough info to infer the correct type for the inline variable.
Asynchronous issues
If you're executing the code using a Async (.NoWait) thread/task, then it might be better to put FData in the local variable. FData, being a dynamic array, is already a pointer (so no copying will take place, just a ref count). And dynamic arrays do not have Copy-on-Write semantics, so the original will get updated.
As is, the Self record might go out of scope whilst the code is running, because the pointer operation S:= #Self does not cause the reference count on FData to increase). This might cause an access violation (or worse).
Taking a reference to FData causes its refcount to go up, meaning it cannot go out of scope prematurely.

Access violation after going out of a RTTI-related function: Result disappears

Previously I had one function to get object property through RTTI and set it's value. Now I decided to split it up in TRTTI.GetObjProp and TRTTI.SetObjPropValue in order to cache value returned by TRTTI.GetObjProp and speed up data processing.
Strange things happen after that. First of all, I suddenly noticed that ctx.GetType works and has always worked although I never initialized the ctx variable. Ok, if I initialize it with TRttiContext.Create(), nothing changes in the second weirdness:
I call the TRTTI.GetObjProp function and as long as I am in this function, Result is defined, and I can request it's properties with debugger. When I go out of the function, I try to request the same properties of rprop variable and get Access Violation error. According to debugger, rprop is defined.
procedure TConfManager._setValue(indicator: TComponent; name: string; value: OleVariant);
var
rprop: TRttiProperty;
begin
rprop := TRTTI.GetObjProp(indicator, name);
//Access violation here when I try to use rprop
TRTTI.SetObjPropValue(indicator, rprop, value);
end;
class function TRTTI.GetObjProp(obj: TObject; propName: string): TRttiProperty;
var
ctx: TRttiContext;
rtyp: TRttiType;
begin
if obj = nil then Exit(nil);
rtyp := ctx.GetType(obj.ClassType);
Result := rtyp.GetProperty(propName);
end;
Why the function result is properly defined when I am in the function, but isn't properly defined when I go out of it?
The TRttiProperty instance is owned by the TRttiContext object. When your local variable ctx leaves scope, that TRttiContext object is destroyed, taking with it all the objects it owns, including your TRttiProperty instance.
You need to make sure that the TRttiContext object that owns any RTTI objects that you use lives at least as long as any references to those owned objects. The simplest way to achieve that is probably to make the TRttiContext object be a global variable.

Disposing pointers to complex records

I have list of pointers to some complex records. Sometimes when I try disposing them I get invalid pointer operation error. I'm not really sure if I'm creating and disposing them properly.
The record looks like this:
type
PFILEDATA = ^TFILEDATA;
TFILEDATA = record
Description80: TFileType80; // that's array[0..80] of WideChar
pFullPath: PVeryLongPath; // this is pointer to array of WideChar
pNext: PFILEDATA; // this is pointer to the next TFILEDATA record
end;
As I understand when I want a pointer to such record I need to initialize the pointer and the dynamic arrays like this:
function GimmeNewData(): PFILEDATA;
begin
New(Result);
New(Result^.pFullPath);
end;
Now to dispose of series of these records I wrote this:
procedure DisposeData(var pData: PFILEDATA);
var pNextData: PFILEDATA;
begin
while pData^.pNext <> nil do begin
pNextData := pData^.pNext; // Save pointer to the next record
Finalize(pData^.pFullPath); // Free dynamic array
Dispose(pData); // Free the record
pData := pNextData;
end;
Finalize(pData^.pFullPath);
Dispose(pData);
pData := nil;
end;
When I run my program in the debug mode (F9) in the Delphi 2010 IDE something weird happens. When I step trough DisposeData code with F8 it appears that program skips Finalize(pData^.pFullPath) line and jumps to Dispose(pData). Is this normal? Also when Dispose(pData) is executed the Local variables window that displays contents of the pointers does not change. Does this mean that dispose fails?
Edit:
PVeryLongPath is:
type
TVeryLongPath = array of WideChar;
PVeryLongPath = ^TVeryLongPath;
Edit2
So I create 2 TFILEDATA records then I dispose them. Then I create the same 2 records again. For some reason this time pNext in the second record is not nil. It points to the 1st record. Disposing this weird thing gets invalid pointer operation error.
Randomly I have inserted pData^.pNext := nil in the DisposeData procedure.
Now the code looks like this:
procedure DisposeData(var pData: PFILEDATA);
var pNextData: PFILEDATA;
begin
while pData <> nil do begin
pNextData := pData^.pNext;
pData^.pNext := nil; // <----
Dispose(pData^.pFullPath);
Dispose(pData);
pData := pNextData;
end;
end;
The error is gone.
I'll try to change PVeryLongPath into TVeryLongPath.
First, if you free something, the contents of pointers to it do not change. That is why you don't see a change in the local variables display.
EDIT: declare pFullPath as TVeryLongPath. This is a reference type already, and you should not use a pointer to such a type. New() doesn't do what you think it does, in such a case.
It would probably be better if you declared it as UnicodeString, or if your Delphi doesn't have that, WideString.
If pFullPath is declared as a dynamic "array of WideChar", then you should not use New() on it. For dynamic arrays, use SetLength() and nothing else. Dispose() will properly dispose of all items in your record, so just do:
New(Result);
SetLength(Result^.pFullPath, size_you_need);
and later:
Dispose(pData);
In normal code, you should never have to call Finalize(). This is all taken care of by Dispose, as long as you pass a pointer of the correct type to Dispose().
FWIW, I would recommend this and this article of mine.
The fact that you accepted Serg's answer indicates that there is something wrong with your node creation code. Your comment to that answer confirms that.
I'm adding this as a new answer because the edits to the question significantly change it.
Linked list code should look like this:
var
Head: PNode=nil;
//this may be a global variable, or better, a field in a class,
//in which case it would be initialized to nil on creation
function AddNode(var Head: PNode): PNode;
begin
New(Result);
Result.Next := Head;
Head := Result;
end;
Notice that we are adding the node to the head of the list. We don't need to initialize Next to nil anywhere because we always assign another node pointer to Next. That rule is important.
I've written this as a function which returns the new node. Since the new node is always added at the head this is somewhat redundant. Because you can ignore function return values it doesn't really do any harm.
Sometimes you may want to initialize the contents of the node when you add new nodes. For example:
function AddNode(var Head: PNode; const Caption: string): PNode;
begin
New(Result);
Result.Caption := Caption;
Result.Next := Head;
Head := Result;
end;
I much prefer this approach. Always make sure that your fields are initialized. If zero initialization is fine for you then you can use AllocMem to create your node.
Here's a more concrete example of using such a method:
type
PNode = ^TNode;
TNode = record
Caption: string;
Next: PNode;
end;
procedure PopulateList(Items: TStrings);
var
Item: string;
begin
for Item in Items do
AddNode(Head, Item);
end;
To destroy the list the code runs like this:
procedure DestroyList(var Head: PNode);
var
Next: PNode;
begin
while Assigned(Head) do begin
Next := Head.Next;
Dispose(Head);
Head := Next;
end;
end;
You can clearly see that this method can only return when Head is nil.
If you encapsulate your linked list in a class then you can make the head pointer a member of the class and avoid the need to pass it around.
The main point I would like to make is that manual memory allocation code is delicate. It is easy to make little mistakes in the details. In situations like that it pays to put the delicate code in helper functions or methods so you only need to write it once. Linked lists are a great example of a problem that loves to be solved with generics. You can write the memory management code once and re-use it for all sorts of different node types.
I recommend that you avoid using a dynamic array of WideChar which is not at all convenient to work with. Instead use string if you have Delphi 2009 or later, or WideString for earlier Delphi versions. Both of these are dynamic string types with WideChar elements. You can assign to them and Delphi deals with all the allocation.
So, assuming that you now have the following record:
TFILEDATA = record
Description80: TFileType80;
pFullPath: WideString;
pNext: PFILEDATA;
end;
you can simplify things considerably.
function GimmeNewData(): PFILEDATA;
begin
New(Result);
end;
procedure DisposeData(var pData: PFILEDATA);
var pNextData: PFILEDATA;
begin
while pData <> nil do begin
pNextData := pData^.pNext;
Dispose(pData);
pData := pNextData;
end;
end;
You should also initialize pNext field to nil - without it you will finally get access violation. Taking into account what was already said in the previous answers, you can change your code as
type
TFileType80 = array[0..80] of WideChar;
PFILEDATA = ^TFILEDATA;
TFILEDATA = record
Description80: TFileType80;
FullPath: WideString;
pNext: PFILEDATA;
end;
function GimmeNewData: PFILEDATA;
begin
New(Result);
Result^.pNext:= nil;
end;
I think most of your problems are caused by the assumption that New() gives you memory that is zeroed out. I'm pretty sure (and I'm also sure someone will correct me if I'm wrong), but Delphi does not guarantee that that is the case. This can be rectified by changing your code to this:
function GimmeNewData(): PFILEDATA;
begin
New(Result);
ZeroMemory(Result, SizeOf(TFILEDATA));
end;
You should always either zero the memory you get allocated for a record, or at least fill all the fields with something else relevant. This behavior is different to objects, which are guaranteed to be zeroed on allocation.
Hope this helps.

Initialise string function result?

I've just been debugging a problem with a function that returns a string that has got me worried. I've always assumed that the implicit Result variable for functions that return a string would be empty at the start of the function call, but the following (simplified) code produced an unexpected result:
function TMyObject.GenerateInfo: string;
procedure AppendInfo(const AppendStr: string);
begin
if(Result > '') then
Result := Result + #13;
Result := Result + AppendStr;
end;
begin
if(ACondition) then
AppendInfo('Some Text');
end;
Calling this function multiple times resulted in:
"Some Text"
the first time,
"Some Text"
"Some Text"
the second time,
"Some Text"
"Some Text"
"Some Text"
the third time, etc.
To fix it I had to initialise the Result:
begin
Result := '';
if(ACondition) then
AppendInfo('Some Text');
end;
Is it necessary to initialise a string function result? Why (technically)? Why does the compiler not emit a warning "W1035 Return value of function 'xxx' might be undefined" for string functions? Do I need to go through all my code to make sure a value is set as it is not reliable to expect an empty string from a function if the result is not explicitly set?
I've tested this in a new test application and the result is the same.
procedure TForm1.Button1Click(Sender: TObject);
var
i: integer;
S: string;
begin
for i := 1 to 5 do
S := GenerateInfo;
ShowMessage(S); // 5 lines!
end;
This is not a bug, but "feature":
For a string, dynamic array, method
pointer, or variant result, the
effects are the same as if the
function result were declared as an
additional var parameter following the
declared parameters. In other words,
the caller passes an additional 32-bit
pointer that points to a variable in
which to return the function result.
I.e. your
function TMyObject.GenerateInfo: string;
Is really this:
procedure TMyObject.GenerateInfo(var Result: string);
Note "var" prefix (not "out" as you may expect!).
This is SUCH un-intuitive, so it leads to all kind of problems in the code. Code in question - just one example of results of this feature.
See and vote for this request.
We've run into this before, I think maybe as far back as Delphi 6 or 7. Yes, even though the compiler doesn't bother to give you a warning, you do need to initialize your string Result variables, for precisely the reason you ran into. The string variable is getting initialized -- it doesn't start as a garbage reference -- but it doesn't seem to get reinitialized when you expect it to.
As for why it happens... not sure. It's a bug, so it doesn't necessarily need a reason. We only saw it happen when we called the function repeatedly in a loop; if we called it outside a loop, it worked as expected. It looked like the caller was allocating space for the Result variable (and reusing it when it called the same function repeatedly, thus causing the bug), rather than the function allocating its own string (and allocating a new one on each call).
If you were using short strings, then the caller does allocate the buffer -- that's long-standing behavior for large value types. But that doesn't make sense for AnsiString. Maybe the compiler team just forgot to change the semantics when they first implemented long strings in Delphi 2.
This is not a Bug. By definition no variable inside function is initialized, including Result.
So your Result is undefind on first call, and can hold anything. How it is implemented in compiler is irrelevant, and you can have different results in different compilers.
It seems like your function should be simplified like this:
function TMyObject.GenerateInfo: string;
begin
if(ACondition) then
Result := 'Some Text'
else
Result := '';
end;
You typically don't want to use Result on the right side of an assignment in a function.
Anyway, strictly for illustrative purposes, you could also do this, though not recommended:
procedure TForm1.Button1Click(Sender: TObject);
var
i: integer;
S: string;
begin
for i := 1 to 5 do
begin
S := ''; // Clear before you call
S := GenerateInfo;
end;
ShowMessage(S); // 5 lines!
end;
This looks like a bug in D2007. I just tested it in Delphi 2010 and got the expected behavior. (1 line instead of 5.)
If you think that some automatic management of strings are made to make your life easier, you're only partly right. All such things are also done to make string logic consistent and side-effects free.
In plenty of places there are string passed by reference, passed by value, but all these lines are expecting VALID strings in whose memory-management counter is some valid, not a garbage value. So in order to keep strings valid the only thing for sure is that they should be initialized when they firstly introduced. For example, for any local variable string this is a necessity since this is the place a string is introduced. All other string usage including function(): string (that actually procedure(var Result: string) as Alexander correctly pointed out) just expects valid strings on the stack, not initialized. And validness here comes from the fact that (var Result: string) construction says that "I'm waiting for a valid variable that definetly was introduced before". UPDATE: Because of that the actual contents of Result is unexpected, but due to the same logic, if it's the only call to this function that has a local variable at the left, the emptiness of the string in this case is guaranteed.
Alex's answer is nearly always right and it answers why I was seeing the strange behaviour that I was, but it isn't the whole story.
The following, compiled without optimisation, produces the expected result of sTemp being an empty string. If you swap the function out for the procedure call you get a different result.
There seems to be a different rule for the actual program unit.
Admittedly this is a corner case.
program Project1;
{$APPTYPE CONSOLE}
uses System.SysUtils;
function PointlessFunction: string;
begin
end;
procedure PointlessProcedure(var AString: string);
begin
end;
var
sTemp: string;
begin
sTemp := '1234';
sTemp := PointlessFunction;
//PointlessProcedure(sTemp);
WriteLn('Result:' + sTemp);
ReadLn;
end.

Array of (pointers to a record)

I want to create a bunch of records (RWell) and to store them in an array in a certain order. Then I want to create a new array (different layout) and rearange the records in it.
Of course, I don't want to duplicate data in RAM so I though that in the second array I should put pointers to the records in the first array. However, I can't do that. Anybody can tell what's wrong with the code below?
Thanks
Type
RWell= record
x: string;
i: integer;
end;
PWell= ^RWell;
RWellArray= Array[0..12, 0..8] of RWell;
procedure TClass1.CreateWells
var
WellMX: RWellArray;
begin
{ should I initialize the WellXM here? }
{ note: WellXM is a static array! }
other stuff
end;
var Wells: array of PWell;
procedure TClass2.AddWell(aWell: RWell);
begin
aWell.Stuff:= stuff; {aWell cannot be readonly because I need to change it here}
SetLength(Wells, Length(Wells)+ 1); { reserve memory }
Wells[High(Wells)]:= #aWell;
end;
procedure TClass3.DisplayWell;
var CurWell: RWell;
begin
CurWell:= CurPrimer.Wells[iCurWell]^; <--- AV here (but in debugger the address is correct)
end;
Solved by Rob K.
In your AddWell function, you're passing the record by value. That means the function gets a copy of the actual parameter. You're storing a pointer to the formal parameter, which is probably just a location on the local stack of the function.
If you want a pointer to a well, then pass a pointer to a well:
procedure AddWell(AWell: PWell);
begin
SetLength(Wells, Length(Wells) + 1);
Wells[High(Wells)] := AWell;
end;
Another option is to pass the record by const value. For records, this means the actual parameter is passed as a reference. A pointer to the formal parameter is also a pointer to the actual parameter:
procedure AddWell(const AWell: RWell);
begin
SetLength(Wells, Length(Wells) + 1);
Wells[High(Wells)] := #AWell;
end;
I wouldn't really rely on that, though. When you want pointers, pass pointers. Some people try to avoid pointers in their code, but they're nothing to be afraid of.

Resources