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

Answers


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.

Which variables are initialized when in Delphi?

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.


Edit

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.

Fix the root cause, not the symptoms


Need Your Help

Php and Javascript slider issue

javascript php html

I have a issue in slider for my php website

DropdownListFor doesn't select (who'd a guessed?)

model-view-controller select html.dropdownlistfor

I have a dropdownlist that will not display the selected value correctly. It does have the correct elements in it, has the correct text and values being used but there just doesn't seem to be a way...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.