4

I have here a problem which I do not understand :

procedure TMain.THREAD_SYNC(
              AProgressBar: TProgressBar; 
              ARemoteData: array of RemoteDATA; 
              ALocalData : array of LocalDATA; 
              Number : integer; 
              AInfo : TEdit);

The following procedure works perfectly if I assign to it "smaller arrays" like this

THREAD_SYNC(Remote,Local,0,Edit1)

When I try to assign a larger array to it with over 30.000 records then I get a Stack Overflow error, so I tried and googled ... and I found something about using const so I changed my procedure to:

procedure TMain.THREAD_SYNC(
              AProgressBar: TProgressBar; 
              ARemoteData: array of RemoteDATA; 
              const ALocalData : array of LocalDATA; 
              Number : integer; 
              AInfo : TEdit);

And now it works, my problem is I don't understand why?
What is the difference without const?

1 Answer 1

6

These arrays are passed by value which means that they are copied onto the stack and passed that way. Hence the stack overflow errors.

The problem is resolved by making the array parameters const. In that scenario the array is passed by reference rather than value. In other words a single pointer is passed.

In general when passing (potentially) large structures like arrays or records you should always pass them by reference; using const if the method receiving them does not alter the data and using var if the receiver does. This has the added benefit that your code becomes faster because no data needs to be copied.

You should probably alter your method like so:

procedure TMain.THREAD_SYNC(
              AProgressBar: TProgressBar; 
              const ARemoteData: array of RemoteDATA; 
              const ALocalData : array of LocalDATA; 
              Number : integer; 
              AInfo : TEdit);

There is no need to use const for TProgressBar or TEdit, these are classes and classes are stored on the heap with only a reference on the stack.

Sign up to request clarification or add additional context in comments.

2 Comments

It behaves that way, but in reality, first a single pointer is passed, and when the parameter is not const, the callee (THREAD_SYNC) copies the array over, using that pointer. The effect is the same though: a stack overflow.
FWIW, this is documented: docwiki.embarcadero.com/RADStudio/Tokyo/en/… : "Value and constant (const) parameters are passed by value or by reference, depending on the type and size of the parameter"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.