delphi: inaccessible value on var parameter
I have this example method below
procedure ReadData(var data:TDataSet) begin if Assigned(data) then data.Free; data:=TDataSet.Create(nil); .... end; ..... procedure SomethingProcedure() var dataSet:TDataset; begin ReadData(dataSet); end;
if I debugged and I place breakpoint on Assigned checking, data.Free always executed, and I saw on watch list, data always inaccessible value
My point is SomethingProcedure is access for many other procedure, and I want data parameter if it assigned (already created TDataset object), free it first, but if not assigned (not created object), free command doesn't execute, but free statement always executed, either "data" object created or not
How I can check my object already created or not
You have some issues with your code example
- You declare dataset but pass data in your Init procedure
- The if statement doesn't have a then in your ReadData procedure
All in all, you can not have been debugging the example you've given so I'm going to make some assumptions here.
I believe your actual problem is coming from the fact that local, not finalized variables do not get initialized to zero/nil. The dataset variable in your Init procedure contains whatever garbage happens to be at the location the variable points to.
As you don't initialize the local variable dataset (something you should always do with local variables), Assigned will return true (all it does is check for nil) and free will get called.
Most of the time and if you are lucky, the call to free will throw an AV. Worst case, it will succeed and you will have a really hard time figuring out why something is going wrong.
I assume by your edit that you mean that ReadData is called in many other procedures?
If that's the case, there really is not a lot you can (or for that matter should) do to protect you from callers passing in garbage. What you should do is fix the callers.