Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2011-08

Suggestions on array allocation pattern/rules of thumb?

1 message · 1 person ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Flávio Etrusco

Hello,
In Lazarus I found (pseudo)some code like this:

procedure DoSomething(...)
var
  v_Results: PInteger;
  v_ResultCount: Integer;
begin
  v_Result := nil;
  PrepareData(..., v_Results, v_ResultCount);
  InternalDoSomething(v_Results, v_ResultCount);
end;
procedure PrepareData(..., var p_Results: PInteger; var p_ResultCount: Integer)
begin
  for (...)
    if (...)
    begin
     Inc(p_ResultCount);
     ReallocMem(p_Results, p_ResultCount);
    end;
end;

As you might guess my main gripe is about the repeated calls to ReallocMem. The real case in the LCL is far from critical, it's infrequently and the array won't ever be bigger than 10 elements, I just thought it could a good example to hear from someone knowledgeable in FPC heap-allocator about any "rules of thumb" :-) Apart from making the parameters 'out' - ;) - what would you do?
1) This is this ok.
2) Allocate a buffer with maximum size and then trim it after the loop.
3) Declare a type for the maximum size, allocate it on the heap (in DoSomething).
4) Declare a type for the maximum size, allocate it on the stack (in DoSomething).
5) Any other options?
Any remarks regarding different scenarios is also appreciated.

Thanks,
Flávio