### Bookstore

 Computer Math and Games in Pascal (preview) Lazarus Handbook

### Author Topic: Recoursively find sizeof the object  (Read 1099 times)

#### Eugene Loza

• Hero Member
• Posts: 570
##### Recoursively find sizeof the object
« on: January 11, 2017, 07:26:48 am »
Hi all!
Is there a way to find (recoursively) the total memory size of the complex object. I.e. of structure like this (pseudocode):
Code: Pascal  [Select][+][-]
1. type TObj1 = class(TObject)
2.   public
3.     arr: array of byte;
4. end;
5. type TObjList = specialize TFPGObjectList<TObj1>;
6. type TObj2 = class(TObj1)
7.   public
8.     children: TObjList;
9.     constructor create;
10. end;
11.
12. constructor TObj2.create;
13. begin
14.   Children := TObjList.create(true);
15. end;
16.
17. var Obj: TObj2;
18.     i,j: integer;
19.     tempObj1,tempObj2: TObj2;
20. begin
21.   randomize;
22.   for i := 0 to 100 do if random>0.5 then begin
23.     TempObj1 := TObj2.create;
24.     setLength(TemObj1.arr,random(1000));
25.     for j := 0 to 100 do if random >0.5 then begin
26.       TempObj2 := TObj2.create;
27.       setLength(TempObj2.arr,random(1000));
29.       {and the tree might go deeper here}
30.     end;
31.   end;
32.   writeln(sizeof(TempObj1)); //<------------------------ that's the goal
33. End.

Yes, I mean that creating a manual (recoursive) funciton TObj1.GetMySize: integer for each object is a bad option.
« Last Edit: January 11, 2017, 07:33:51 am by Eugene Loza »
Lazarus 1.9 + FPC 3.1.1 Debian Jessie 64 bit.

My Free and Open Source games in Lazarus/FreePascal/CastleGameEngine:
https://decoherence.itch.io/
(and some ancient games in Turbo Pascal too)
Sources are here: https://github.com/eugeneloza?tab=repositories