瀏覽代碼

Merge branch source:main into main

Curtis Hamilton 1 月之前
父節點
當前提交
139482ddf5
共有 100 個文件被更改,包括 866 次插入108 次删除
  1. 15 2
      compiler/aasmcnst.pas
  2. 12 3
      compiler/aasmdata.pas
  3. 1 0
      compiler/aasmdef.pas
  4. 1 0
      compiler/aggas.pas
  5. 3 1
      compiler/aopt.pas
  6. 6 3
      compiler/aoptobj.pas
  7. 6 1
      compiler/assemble.pas
  8. 1 0
      compiler/blockutl.pas
  9. 14 11
      compiler/cclasses.pas
  10. 1 0
      compiler/cfidwarf.pas
  11. 4 0
      compiler/cfileutl.pas
  12. 2 0
      compiler/cg64f32.pas
  13. 6 0
      compiler/comprsrc.pas
  14. 1 1
      compiler/cprofile.pas
  15. 4 0
      compiler/cresstr.pas
  16. 1 0
      compiler/cscript.pas
  17. 2 0
      compiler/cstreams.pas
  18. 1 0
      compiler/ctask.pas
  19. 1 0
      compiler/dbgbase.pas
  20. 9 0
      compiler/dbgdwarf.pas
  21. 3 0
      compiler/dbgstabs.pas
  22. 1 0
      compiler/entfile.pas
  23. 1 0
      compiler/export.pas
  24. 1 0
      compiler/expunix.pas
  25. 2 1
      compiler/finput.pas
  26. 55 6
      compiler/fmodule.pas
  27. 2 0
      compiler/fpcp.pas
  28. 4 1
      compiler/fpkg.pas
  29. 1 0
      compiler/fppu.pas
  30. 2 0
      compiler/gendef.pas
  31. 10 0
      compiler/globals.pas
  32. 16 3
      compiler/htypechk.pas
  33. 1 0
      compiler/import.pas
  34. 23 2
      compiler/link.pas
  35. 2 0
      compiler/machoutils.pas
  36. 1 1
      compiler/nadd.pas
  37. 7 3
      compiler/nbas.pas
  38. 25 1
      compiler/ncal.pas
  39. 3 0
      compiler/ncgcon.pas
  40. 3 0
      compiler/ncgflw.pas
  41. 16 0
      compiler/ncgrtti.pas
  42. 6 0
      compiler/ncgvmt.pas
  43. 11 2
      compiler/ncnv.pas
  44. 22 1
      compiler/nflw.pas
  45. 20 0
      compiler/ngenutil.pas
  46. 22 0
      compiler/ngtcon.pas
  47. 13 4
      compiler/ninl.pas
  48. 1 0
      compiler/nmat.pas
  49. 2 0
      compiler/nobj.pas
  50. 3 0
      compiler/node.pas
  51. 9 6
      compiler/nset.pas
  52. 1 0
      compiler/objcdef.pas
  53. 31 0
      compiler/objcgutl.pas
  54. 40 9
      compiler/ogbase.pas
  55. 5 0
      compiler/ogcoff.pas
  56. 9 0
      compiler/ogelf.pas
  57. 7 1
      compiler/ogmacho.pas
  58. 4 0
      compiler/ognlm.pas
  59. 83 1
      compiler/ogomf.pas
  60. 1 0
      compiler/ogrel.pas
  61. 25 7
      compiler/ogwasm.pas
  62. 4 2
      compiler/omfbase.pas
  63. 1 0
      compiler/optconstprop.pas
  64. 7 6
      compiler/optcse.pas
  65. 2 0
      compiler/optdfa.pas
  66. 11 0
      compiler/options.pas
  67. 1 0
      compiler/optloop.pas
  68. 2 0
      compiler/opttail.pas
  69. 8 0
      compiler/optvirt.pas
  70. 6 0
      compiler/owar.pas
  71. 2 0
      compiler/owbase.pas
  72. 17 0
      compiler/owomflib.pas
  73. 1 0
      compiler/paramgr.pas
  74. 8 2
      compiler/parser.pas
  75. 1 0
      compiler/pass_1.pas
  76. 13 5
      compiler/pdecl.pas
  77. 3 0
      compiler/pdecobj.pas
  78. 5 1
      compiler/pdecsub.pas
  79. 17 5
      compiler/pdecvar.pas
  80. 2 0
      compiler/pexports.pas
  81. 26 5
      compiler/pexpr.pas
  82. 1 0
      compiler/pgentype.pas
  83. 26 3
      compiler/pgenutil.pas
  84. 12 0
      compiler/pinline.pas
  85. 11 0
      compiler/pkgutil.pas
  86. 10 0
      compiler/pmodules.pas
  87. 5 2
      compiler/procdefutil.pas
  88. 6 0
      compiler/procinfo.pas
  89. 7 0
      compiler/psabiehpi.pas
  90. 13 1
      compiler/pstatmnt.pas
  91. 5 0
      compiler/psub.pas
  92. 1 0
      compiler/ptconst.pas
  93. 6 0
      compiler/ptype.pas
  94. 2 0
      compiler/rasm.pas
  95. 2 1
      compiler/rautils.pas
  96. 7 1
      compiler/rgobj.pas
  97. 24 2
      compiler/scanner.pas
  98. 1 0
      compiler/switches.pas
  99. 3 0
      compiler/symbase.pas
  100. 2 1
      compiler/symcreat.pas

+ 15 - 2
compiler/aasmcnst.pas

@@ -665,6 +665,7 @@ implementation
    destructor tai_simpletypedconst.destroy;
    destructor tai_simpletypedconst.destroy;
      begin
      begin
        fval.free;
        fval.free;
+       fval := nil;
        inherited destroy;
        inherited destroy;
      end;
      end;
 
 
@@ -719,7 +720,7 @@ implementation
             if ai.adetyp<>tck_simple then
             if ai.adetyp<>tck_simple then
               internalerror(2014070103);
               internalerror(2014070103);
             add_to_string(newstr,tai_simpletypedconst(ai).val);
             add_to_string(newstr,tai_simpletypedconst(ai).val);
-            ai.free;
+            ai.free; // no nil needed
           end;
           end;
        fvalues.count:=0;
        fvalues.count:=0;
        { the "nil" def will be replaced with an array def of the appropriate
        { the "nil" def will be replaced with an array def of the appropriate
@@ -787,7 +788,8 @@ implementation
              1:
              1:
                begin
                begin
                  add_to_string(tai_string(tai_simpletypedconst(fvalues[0]).val),tai_simpletypedconst(val).val);
                  add_to_string(tai_string(tai_simpletypedconst(fvalues[0]).val),tai_simpletypedconst(val).val);
-                 val.free
+                 val.free;
+                 val := nil;
                end
                end
              else
              else
                internalerror(2014070104);
                internalerror(2014070104);
@@ -849,6 +851,7 @@ implementation
    destructor tai_aggregatetypedconst.destroy;
    destructor tai_aggregatetypedconst.destroy;
      begin
      begin
        fvalues.free;
        fvalues.free;
+       fvalues := nil;
        inherited destroy;
        inherited destroy;
      end;
      end;
 
 
@@ -1044,6 +1047,7 @@ implementation
        fasmlist.concat(tai_symbol_end.Createname(asmsym.name));
        fasmlist.concat(tai_symbol_end.Createname(asmsym.name));
        { free the temporary list }
        { free the temporary list }
        prelist.free;
        prelist.free;
+       prelist := nil;
      end;
      end;
 
 
 
 
@@ -1077,6 +1081,7 @@ implementation
            symind.increfs;
            symind.increfs;
 
 
            indtcb.free;
            indtcb.free;
+           indtcb := nil;
            if not (target_info.system in systems_indirect_var_imports) then
            if not (target_info.system in systems_indirect_var_imports) then
              current_module.add_public_asmsym(symind.name,AB_INDIRECT,AT_DATA);
              current_module.add_public_asmsym(symind.name,AB_INDIRECT,AT_DATA);
          end;
          end;
@@ -1274,7 +1279,9 @@ implementation
           (ErrorCount=0) then
           (ErrorCount=0) then
          internalerror(2014062901);
          internalerror(2014062901);
        faggregateinformation.free;
        faggregateinformation.free;
+       faggregateinformation := nil;
        fasmlist.free;
        fasmlist.free;
+       fasmlist := nil;
        inherited destroy;
        inherited destroy;
      end;
      end;
 
 
@@ -1559,6 +1566,7 @@ implementation
        info:=curagginfo;
        info:=curagginfo;
        faggregateinformation.count:=faggregateinformation.count-1;
        faggregateinformation.count:=faggregateinformation.count-1;
        info.free;
        info.free;
+       info := nil;
      end;
      end;
 
 
 
 
@@ -1826,6 +1834,7 @@ implementation
        { we emit the high value, not the count }
        { we emit the high value, not the count }
        arrlengthloc.replace(tai_const.Create_sizeint(arrlength-1),sizesinttype);
        arrlengthloc.replace(tai_const.Create_sizeint(arrlength-1),sizesinttype);
        arrlengthloc.free;
        arrlengthloc.free;
+       arrlengthloc := nil;
        if get_dynarray_symofs=0 then
        if get_dynarray_symofs=0 then
          emit_tai(tai_symbol_end.create(llofs.lab),arrdef);
          emit_tai(tai_symbol_end.create(llofs.lab),arrdef);
        result:=end_anonymous_record;
        result:=end_anonymous_record;
@@ -1940,6 +1949,7 @@ implementation
              strtcb.get_final_asmlist(strlab,datadef,sec_rodata_norel,strlab.name,const_align(sizeof(pint)))
              strtcb.get_final_asmlist(strlab,datadef,sec_rodata_norel,strlab.name,const_align(sizeof(pint)))
            );
            );
            strtcb.free;
            strtcb.free;
+           strtcb := nil;
 
 
            entry^.Data:=strlab;
            entry^.Data:=strlab;
            { Make sure strlab has a reference }
            { Make sure strlab has a reference }
@@ -2158,7 +2168,9 @@ implementation
        for i:=high(fields) downto low(fields) do
        for i:=high(fields) downto low(fields) do
          queue_subscriptn(tabstractrecorddef(parentdefs[i]),tfieldvarsym(syms[i]));
          queue_subscriptn(tabstractrecorddef(parentdefs[i]),tfieldvarsym(syms[i]));
        syms.free;
        syms.free;
+       syms := nil;
        parentdefs.free;
        parentdefs.free;
+       parentdefs := nil;
      end;
      end;
 
 
 
 
@@ -2266,6 +2278,7 @@ implementation
        list.insertafter(ai,insertpos);
        list.insertafter(ai,insertpos);
        list.remove(insertpos);
        list.remove(insertpos);
        insertpos.free;
        insertpos.free;
+       insertpos := nil;
      end;
      end;
 
 
 
 

+ 12 - 3
compiler/aasmdata.pas

@@ -32,7 +32,7 @@ unit aasmdata;
 interface
 interface
 
 
     uses
     uses
-       cutils,cclasses,
+       sysutils,cutils,cclasses,
        globtype,systems,
        globtype,systems,
        cgbase,
        cgbase,
        symtype,
        symtype,
@@ -556,7 +556,9 @@ implementation
         memasmsymbols.start;
         memasmsymbols.start;
 {$endif}
 {$endif}
         FAltSymbolList.free;
         FAltSymbolList.free;
+        FAltSymbolList := nil;
         FAsmSymbolDict.free;
         FAsmSymbolDict.free;
+        FAsmSymbolDict := nil;
 {$ifdef MEMDEBUG}
 {$ifdef MEMDEBUG}
         memasmsymbols.stop;
         memasmsymbols.stop;
 {$endif}
 {$endif}
@@ -565,6 +567,7 @@ implementation
         memasmcfi.start;
         memasmcfi.start;
 {$endif}
 {$endif}
         FAsmCFI.free;
         FAsmCFI.free;
+        FAsmCFI := nil;
 {$ifdef MEMDEBUG}
 {$ifdef MEMDEBUG}
         memasmcfi.stop;
         memasmcfi.stop;
 {$endif}
 {$endif}
@@ -573,15 +576,18 @@ implementation
          memasmlists.start;
          memasmlists.start;
 {$endif}
 {$endif}
         ResStrInits.free;
         ResStrInits.free;
+        ResStrInits := nil;
         WideInits.free;
         WideInits.free;
+        WideInits := nil;
          for hal:=low(TAsmListType) to high(TAsmListType) do
          for hal:=low(TAsmListType) to high(TAsmListType) do
-           AsmLists[hal].free;
+           FreeAndNil(AsmLists[hal]);
          CurrAsmList.free;
          CurrAsmList.free;
+         CurrAsmList := nil;
 {$ifdef MEMDEBUG}
 {$ifdef MEMDEBUG}
          memasmlists.stop;
          memasmlists.stop;
 {$endif}
 {$endif}
          for hp := low(TConstPoolType) to high(TConstPoolType) do
          for hp := low(TConstPoolType) to high(TConstPoolType) do
-           FConstPools[hp].Free;
+           FreeAndNil(FConstPools[hp]);
       end;
       end;
 
 
     function TAsmData.DefineAsmSymbolByClass(symclass: TAsmSymbolClass; const s: TSymStr; _bind: TAsmSymBind; _typ: Tasmsymtype; def: tdef): TAsmSymbol;
     function TAsmData.DefineAsmSymbolByClass(symclass: TAsmSymbolClass; const s: TSymStr; _bind: TAsmSymBind; _typ: Tasmsymtype; def: tdef): TAsmSymbol;
@@ -763,8 +769,11 @@ initialization
 finalization
 finalization
 {$ifdef MEMDEBUG}
 {$ifdef MEMDEBUG}
   memasmsymbols.free;
   memasmsymbols.free;
+  memasmsymbols := nil;
   memasmcfi.free;
   memasmcfi.free;
+  memasmcfi := nil;
   memasmlists.free;
   memasmlists.free;
+  memasmlists := nil;
 {$endif MEMDEBUG}
 {$endif MEMDEBUG}
 
 
 end.
 end.

+ 1 - 0
compiler/aasmdef.pas

@@ -75,6 +75,7 @@ function TAsmDataDef.DefineAsmSymbolByClass(symclass: TAsmSymbolClass; const s:
           lower(symind.name),
           lower(symind.name),
           ptrdef.alignment));
           ptrdef.alignment));
         tcb.free;
         tcb.free;
+        tcb := nil;
         if (_typ=AT_DATA_FORCEINDIRECT) and not (target_info.system in systems_indirect_var_imports) then
         if (_typ=AT_DATA_FORCEINDIRECT) and not (target_info.system in systems_indirect_var_imports) then
           current_module.add_public_asmsym(symind.name,AB_INDIRECT,AT_DATA);
           current_module.add_public_asmsym(symind.name,AB_INDIRECT,AT_DATA);
       end;
       end;

+ 1 - 0
compiler/aggas.pas

@@ -177,6 +177,7 @@ implementation
     destructor TGNUAssembler.Destroy;
     destructor TGNUAssembler.Destroy;
       begin
       begin
         InstrWriter.free;
         InstrWriter.free;
+        InstrWriter := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 

+ 3 - 1
compiler/aopt.pas

@@ -379,6 +379,7 @@ Unit aopt;
         p.Debug_InsertInstrRegisterDependencyInfo;
         p.Debug_InsertInstrRegisterDependencyInfo;
 {$endif DEBUG_INSTRUCTIONREGISTERDEPENDENCIES}
 {$endif DEBUG_INSTRUCTIONREGISTERDEPENDENCIES}
         p.free;
         p.free;
+        p := nil;
         StopTimer;
         StopTimer;
       end;
       end;
 
 
@@ -389,7 +390,8 @@ Unit aopt;
       begin
       begin
         p:=cpreregallocscheduler.Create(AsmL);
         p:=cpreregallocscheduler.Create(AsmL);
         p.Optimize;
         p.Optimize;
-        p.free
+        p.free;
+        p := nil;
       end;
       end;
 
 
 
 

+ 6 - 3
compiler/aoptobj.pas

@@ -38,7 +38,7 @@ Unit AoptObj;
   Interface
   Interface
 
 
     uses
     uses
-      globtype,
+      sysutils,globtype,
       aasmbase,aasmcpu,aasmtai,aasmdata,
       aasmbase,aasmcpu,aasmtai,aasmdata,
       cclasses,
       cclasses,
       cgbase,cgutils,
       cgbase,cgutils,
@@ -1227,7 +1227,7 @@ Unit AoptObj;
           i : TRegisterType;
           i : TRegisterType;
       begin
       begin
         for i:=low(TRegisterType) to high(TRegisterType) do
         for i:=low(TRegisterType) to high(TRegisterType) do
-          regs[i].Free;
+          regs[i].free; // no nil needed
       end;
       end;
 
 
 
 
@@ -1671,7 +1671,7 @@ Unit AoptObj;
     procedure TAOptObj.RemoveInstruction(const hp: tai); inline;
     procedure TAOptObj.RemoveInstruction(const hp: tai); inline;
       begin
       begin
         AsmL.Remove(hp);
         AsmL.Remove(hp);
-        hp.Free;
+        hp.Free; // no nil needed
       end;
       end;
 
 
 
 
@@ -1761,6 +1761,7 @@ Unit AoptObj;
           begin
           begin
             asml.remove(hp2);
             asml.remove(hp2);
             hp2.free;
             hp2.free;
+            hp2 := nil;
           end;
           end;
         { Anything except A_NOP must be left in place: these instructions
         { Anything except A_NOP must be left in place: these instructions
           execute before branch, so code stays correct if branch is removed. }
           execute before branch, so code stays correct if branch is removed. }
@@ -1871,6 +1872,7 @@ Unit AoptObj;
                     end;
                     end;
                   asml.remove(hp1);
                   asml.remove(hp1);
                   hp1.free;
                   hp1.free;
+                  hp1 := nil;
                 end
                 end
               else
               else
                 p:=hp1;
                 p:=hp1;
@@ -2090,6 +2092,7 @@ Unit AoptObj;
 {$endif EXTDEBUG}
 {$endif EXTDEBUG}
                 asml.Remove(hp);
                 asml.Remove(hp);
                 hp.Free;
                 hp.Free;
+                hp := nil;
                 Exit;
                 Exit;
               end;
               end;
             else
             else

+ 6 - 1
compiler/assemble.pas

@@ -1403,7 +1403,7 @@ Implementation
     destructor TExternalAssembler.Destroy;
     destructor TExternalAssembler.Destroy;
       begin
       begin
         if ffreewriter then
         if ffreewriter then
-          writer.Free;
+          writer.Free; // no nil needed
         inherited;
         inherited;
       end;
       end;
 
 
@@ -1428,8 +1428,10 @@ Implementation
       begin
       begin
         if assigned(ObjData) then
         if assigned(ObjData) then
           ObjData.free;
           ObjData.free;
+          ObjData := nil;
         if assigned(ObjOutput) then
         if assigned(ObjOutput) then
           ObjOutput.free;
           ObjOutput.free;
+          ObjOutput := nil;
       end;
       end;
 
 
 
 
@@ -2766,6 +2768,7 @@ Implementation
         ObjData.free;
         ObjData.free;
         ObjData:=nil;
         ObjData:=nil;
         ObjWriter.free;
         ObjWriter.free;
+        ObjWriter := nil;
       end;
       end;
 
 
 
 
@@ -2881,6 +2884,7 @@ Implementation
         ObjData.free;
         ObjData.free;
         ObjData:=nil;
         ObjData:=nil;
         ObjWriter.free;
         ObjWriter.free;
+        ObjWriter := nil;
       end;
       end;
 
 
 
 
@@ -2926,6 +2930,7 @@ Implementation
         a:=CAssembler[target_asm.id].Create(@target_asm,smart);
         a:=CAssembler[target_asm.id].Create(@target_asm,smart);
         a.MakeObject;
         a.MakeObject;
         a.Free;
         a.Free;
+        a := nil;
       end;
       end;
 
 
 
 

+ 1 - 0
compiler/blockutl.pas

@@ -373,6 +373,7 @@ implementation
         end;
         end;
 
 
       procvarnode.free;
       procvarnode.free;
+      procvarnode := nil;
 
 
       { restore scanner }
       { restore scanner }
       restore_scanner(sstate);
       restore_scanner(sstate);

+ 14 - 11
compiler/cclasses.pas

@@ -1059,7 +1059,7 @@ begin
     exit;
     exit;
   Lp := Lst.FList;
   Lp := Lst.FList;
   for I := 0 to Lst.Count-1 do
   for I := 0 to Lst.Count-1 do
-    TObject(Lp[I]).Free;
+    TObject(Lp[I]).Free; // no nil needed
   Lst.Free;
   Lst.Free;
   Lst := nil;
   Lst := nil;
 end;
 end;
@@ -1112,7 +1112,7 @@ var
 begin
 begin
   if FFreeObjects then
   if FFreeObjects then
     for i := 0 to FList.Count - 1 do
     for i := 0 to FList.Count - 1 do
-      TObject(FList[i]).Free;
+      TObject(FList[i]).Free; // no nil needed
   FList.Clear;
   FList.Clear;
 end;
 end;
 
 
@@ -1152,7 +1152,7 @@ end;
 procedure TFPObjectList.SetItem(Index: Integer; AObject: TObject);
 procedure TFPObjectList.SetItem(Index: Integer; AObject: TObject);
 begin
 begin
   if OwnsObjects then
   if OwnsObjects then
-    TObject(FList[Index]).Free;
+    TObject(FList[Index]).Free; // no nil needed
   FList[index] := AObject;
   FList[index] := AObject;
 end;
 end;
 
 
@@ -1174,7 +1174,7 @@ end;
 procedure TFPObjectList.Delete(Index: Integer);
 procedure TFPObjectList.Delete(Index: Integer);
 begin
 begin
   if OwnsObjects then
   if OwnsObjects then
-    TObject(FList[Index]).Free;
+    TObject(FList[Index]).Free; // no nil needed
   FList.Delete(Index);
   FList.Delete(Index);
 end;
 end;
 
 
@@ -1200,7 +1200,7 @@ begin
   if (Result <> -1) then
   if (Result <> -1) then
   begin
   begin
     if OwnsObjects then
     if OwnsObjects then
-      TObject(FList[Result]).Free;
+      TObject(FList[Result]).Free; // no nil needed
     FList.Delete(Result);
     FList.Delete(Result);
   end;
   end;
 end;
 end;
@@ -1893,7 +1893,7 @@ var
 begin
 begin
   if FFreeObjects then
   if FFreeObjects then
     for i := 0 to FHashList.Count - 1 do
     for i := 0 to FHashList.Count - 1 do
-      TObject(FHashList[i]).Free;
+      TObject(FHashList[i]).Free; // no nil needed
   FHashList.Clear;
   FHashList.Clear;
 end;
 end;
 
 
@@ -1921,7 +1921,7 @@ end;
 procedure TFPHashObjectList.SetItem(Index: Integer; AObject: TObject);
 procedure TFPHashObjectList.SetItem(Index: Integer; AObject: TObject);
 begin
 begin
   if OwnsObjects then
   if OwnsObjects then
-    TObject(FHashList[Index]).Free;
+    TObject(FHashList[Index]).Free; // no nil needed
   FHashList[index] := AObject;
   FHashList[index] := AObject;
 end;
 end;
 
 
@@ -1958,7 +1958,7 @@ end;
 procedure TFPHashObjectList.Delete(Index: Integer);
 procedure TFPHashObjectList.Delete(Index: Integer);
 begin
 begin
   if OwnsObjects then
   if OwnsObjects then
-    TObject(FHashList[Index]).Free;
+    TObject(FHashList[Index]).Free; // no nil needed
   FHashList.Delete(Index);
   FHashList.Delete(Index);
 end;
 end;
 
 
@@ -1979,7 +1979,7 @@ begin
   if (Result <> -1) then
   if (Result <> -1) then
     begin
     begin
       if OwnsObjects then
       if OwnsObjects then
-        TObject(FHashList[Result]).Free;
+        TObject(FHashList[Result]).Free; // no nil needed
       FHashList.Delete(Result);
       FHashList.Delete(Result);
     end;
     end;
 end;
 end;
@@ -2541,6 +2541,7 @@ end;
          begin
          begin
            inherited Remove(p);
            inherited Remove(p);
            p.Free;
            p.Free;
+           p := nil;
          end;
          end;
       end;
       end;
 
 
@@ -2556,6 +2557,7 @@ end;
           begin
           begin
             GetFirst:=p.FPStr;
             GetFirst:=p.FPStr;
             p.free;
             p.free;
+            p := nil;
           end;
           end;
       end;
       end;
 
 
@@ -2571,6 +2573,7 @@ end;
           begin
           begin
             Getlast:=p.FPStr;
             Getlast:=p.FPStr;
             p.free;
             p.free;
+            p := nil;
           end;
           end;
       end;
       end;
 
 
@@ -2985,7 +2988,7 @@ end;
           begin
           begin
             next := item^.Next;
             next := item^.Next;
             if FOwnsObjects then
             if FOwnsObjects then
-              item^.Data.Free;
+              FreeAndNil(item^.Data);
             FreeItem(item);
             FreeItem(item);
             item := next;
             item := next;
           end;
           end;
@@ -3136,7 +3139,7 @@ end;
               begin
               begin
                 chain^ := Entry^.Next;
                 chain^ := Entry^.Next;
                 if FOwnsObjects then
                 if FOwnsObjects then
-                  Entry^.Data.Free;
+                  FreeAndNil(Entry^.Data);
                 FreeItem(Entry);
                 FreeItem(Entry);
                 Dec(FCount);
                 Dec(FCount);
                 Result := True;
                 Result := True;

+ 1 - 0
compiler/cfidwarf.pas

@@ -271,6 +271,7 @@ implementation
     destructor TDwarfAsmCFILowLevel.destroy;
     destructor TDwarfAsmCFILowLevel.destroy;
       begin
       begin
         FDwarfList.Free;
         FDwarfList.Free;
+        FDwarfList := nil;
       end;
       end;
 
 
 
 

+ 4 - 0
compiler/cfileutl.pas

@@ -219,6 +219,7 @@ end;
       begin
       begin
         FreeDirectoryEntries;
         FreeDirectoryEntries;
         FDirectoryEntries.Free;
         FDirectoryEntries.Free;
+        FDirectoryEntries := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -390,6 +391,7 @@ end;
     destructor TDirectoryCache.destroy;
     destructor TDirectoryCache.destroy;
       begin
       begin
         FDirectories.Free;
         FDirectories.Free;
+        FDirectories := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -1116,6 +1118,7 @@ end;
              Insert(s);
              Insert(s);
            end;
            end;
           hl.Free;
           hl.Free;
+          hl := nil;
         end
         end
        else
        else
         begin
         begin
@@ -1556,6 +1559,7 @@ end;
     procedure DoneFileUtils;
     procedure DoneFileUtils;
       begin
       begin
         DirCache.Free;
         DirCache.Free;
+        DirCache := nil;
       end;
       end;
 
 
 end.
 end.

+ 2 - 0
compiler/cg64f32.pas

@@ -1008,6 +1008,7 @@ unit cg64f32;
 
 
              hlcg.g_rangecheck(list,temploc,hdef,todef);
              hlcg.g_rangecheck(list,temploc,hdef,todef);
              hdef.free;
              hdef.free;
+             hdef := nil;
 
 
              if from_signed and to_signed then
              if from_signed and to_signed then
                begin
                begin
@@ -1041,6 +1042,7 @@ unit cg64f32;
                  temploc.size:=OS_32;
                  temploc.size:=OS_32;
                  hlcg.g_rangecheck(list,temploc,hdef,todef);
                  hlcg.g_rangecheck(list,temploc,hdef,todef);
                  hdef.free;
                  hdef.free;
+                 hdef := nil;
                  cg.a_label(list,endlabel);
                  cg.a_label(list,endlabel);
                end;
                end;
            end
            end

+ 6 - 0
compiler/comprsrc.pas

@@ -244,6 +244,7 @@ destructor TWinLikeResourceFile.Destroy;
 begin
 begin
   if fResScript<>nil then
   if fResScript<>nil then
     fResScript.Free;
     fResScript.Free;
+    fResScript := nil;
   inherited;
   inherited;
 end;
 end;
 
 
@@ -450,7 +451,9 @@ begin
     end;
     end;
   dst.CopyFrom(src,src.Size);
   dst.CopyFrom(src,src.Size);
   dst.Free;
   dst.Free;
+  dst := nil;
   src.Free;
   src.Free;
+  src := nil;
   Result:=true;
   Result:=true;
 end;
 end;
  
  
@@ -486,6 +489,7 @@ begin
       if resourcefile.IsCompiled(s) then
       if resourcefile.IsCompiled(s) then
         begin
         begin
           resourcefile.free;
           resourcefile.free;
+          resourcefile := nil;
           if AnsiCompareFileName(IncludeTrailingPathDelimiter(ExpandFileName(current_module.outputpath)), p) <> 0 then
           if AnsiCompareFileName(IncludeTrailingPathDelimiter(ExpandFileName(current_module.outputpath)), p) <> 0 then
             begin
             begin
               { Copy .res file to units output dir. Otherwise .res file will not be found
               { Copy .res file to units output dir. Otherwise .res file will not be found
@@ -510,6 +514,7 @@ begin
             end;
             end;
           resourcefile.compile(outfmt, current_module.outputpath+res.FPStr);
           resourcefile.compile(outfmt, current_module.outputpath+res.FPStr);
           resourcefile.free;
           resourcefile.free;
+          resourcefile := nil;
         end;
         end;
       res:=TCmdStrListItem(res.Next);
       res:=TCmdStrListItem(res.Next);
     end;
     end;
@@ -564,6 +569,7 @@ begin
   { Finish collection }
   { Finish collection }
   resourcefile.EndCollect;
   resourcefile.EndCollect;
   resourcefile.free;
   resourcefile.free;
+  resourcefile := nil;
 end;
 end;
 
 
 procedure initglobals;
 procedure initglobals;

+ 1 - 1
compiler/cprofile.pas

@@ -106,7 +106,7 @@ finalization
   for t:=low(timers) to high(timers) do
   for t:=low(timers) to high(timers) do
     writeln(StdErr,'  ',t,' ',timers[t].Elapsed:0:9,' s');
     writeln(StdErr,'  ',t,' ',timers[t].Elapsed:0:9,' s');
   for t:=low(timers) to high(timers) do
   for t:=low(timers) to high(timers) do
-    timers[t].Free;
+    FreeAndNil(timers[t]);
 {$endif COMPILER_TIMINGS}
 {$endif COMPILER_TIMINGS}
 end.
 end.
 
 

+ 4 - 0
compiler/cresstr.pas

@@ -161,6 +161,7 @@ uses
     Destructor Tresourcestrings.Destroy;
     Destructor Tresourcestrings.Destroy;
       begin
       begin
         List.Free;
         List.Free;
+        List := nil;
       end;
       end;
 
 
 
 
@@ -235,6 +236,7 @@ uses
             );
             );
             R:=TResourceStringItem(R.Next);
             R:=TResourceStringItem(R.Next);
             tcb.free;
             tcb.free;
+            tcb := nil;
           end;
           end;
         tcb:=ctai_typedconstbuilder.create([tcalo_vectorized_dead_strip_end,tcalo_data_force_indirect,tcalo_is_public_asm]);
         tcb:=ctai_typedconstbuilder.create([tcalo_vectorized_dead_strip_end,tcalo_data_force_indirect,tcalo_is_public_asm]);
         tcb.begin_anonymous_record(internaltypeprefixName[itp_emptyrec],
         tcb.begin_anonymous_record(internaltypeprefixName[itp_emptyrec],
@@ -246,6 +248,7 @@ uses
           )
           )
         );
         );
         tcb.free;
         tcb.free;
+        tcb := nil;
       end;
       end;
 
 
     procedure Tresourcestrings.WriteRSJFile;
     procedure Tresourcestrings.WriteRSJFile;
@@ -368,6 +371,7 @@ uses
             resstrs.WriteRSJFile;
             resstrs.WriteRSJFile;
           end;
           end;
         resstrs.Free;
         resstrs.Free;
+        resstrs := nil;
         symtablestack.pop(current_module.localsymtable);
         symtablestack.pop(current_module.localsymtable);
         if assigned(current_module.globalsymtable) then
         if assigned(current_module.globalsymtable) then
           symtablestack.pop(current_module.globalsymtable);
           symtablestack.pop(current_module.globalsymtable);

+ 1 - 0
compiler/cscript.pas

@@ -156,6 +156,7 @@ end;
 destructor TScript.Destroy;
 destructor TScript.Destroy;
 begin
 begin
   data.Free;
   data.Free;
+  data := nil;
 end;
 end;
 
 
 
 

+ 2 - 0
compiler/cstreams.pas

@@ -623,6 +623,7 @@ begin
     SaveToStream(S);
     SaveToStream(S);
   finally
   finally
     S.free;
     S.free;
+    S := nil;
   end;
   end;
 end;
 end;
 
 
@@ -711,6 +712,7 @@ begin
     LoadFromStream(S);
     LoadFromStream(S);
   finally
   finally
     S.free;
     S.free;
+    S := nil;
   end;
   end;
 end;
 end;
 
 

+ 1 - 0
compiler/ctask.pas

@@ -164,6 +164,7 @@ end;
 destructor ttask_handler.destroy;
 destructor ttask_handler.destroy;
 begin
 begin
   hash.free;
   hash.free;
+  hash := nil;
   List.Clear;
   List.Clear;
   FreeAndNil(list);
   FreeAndNil(list);
   inherited destroy;
   inherited destroy;

+ 1 - 0
compiler/dbgbase.pas

@@ -348,6 +348,7 @@ implementation
             looplist := deftowritelist;
             looplist := deftowritelist;
           end;
           end;
         templist.free;
         templist.free;
+        templist := nil;
       end;
       end;
 
 
 
 

+ 9 - 0
compiler/dbgdwarf.pas

@@ -471,6 +471,7 @@ implementation
     destructor TDirIndexItem.Destroy;
     destructor TDirIndexItem.Destroy;
       begin
       begin
         FFiles.Free;
         FFiles.Free;
+        FFiles := nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;
 
 
@@ -1084,6 +1085,7 @@ implementation
         append_block1(DW_AT_frame_base,blocksize);
         append_block1(DW_AT_frame_base,blocksize);
         current_asmdata.asmlists[al_dwarf_info].concatlist(templist);
         current_asmdata.asmlists[al_dwarf_info].concatlist(templist);
         templist.free;
         templist.free;
+        templist := nil;
       end;
       end;
 {$elseif defined(wasm)}
 {$elseif defined(wasm)}
       var
       var
@@ -1103,6 +1105,7 @@ implementation
               append_block1(DW_AT_frame_base,blocksize);
               append_block1(DW_AT_frame_base,blocksize);
               current_asmdata.asmlists[al_dwarf_info].concatlist(templist);
               current_asmdata.asmlists[al_dwarf_info].concatlist(templist);
               templist.free;
               templist.free;
+              templist := nil;
             end;
             end;
       end;
       end;
 {$else}
 {$else}
@@ -1144,6 +1147,7 @@ implementation
         append_block1(DW_AT_segment,blocksize);
         append_block1(DW_AT_segment,blocksize);
         current_asmdata.asmlists[al_dwarf_info].concatlist(templist);
         current_asmdata.asmlists[al_dwarf_info].concatlist(templist);
         templist.free;
         templist.free;
+        templist := nil;
       end;
       end;
 {$endif i8086}
 {$endif i8086}
 
 
@@ -2646,6 +2650,7 @@ implementation
 {$endif i8086}
 {$endif i8086}
 
 
         templist.free;
         templist.free;
+        templist := nil;
 
 
         finish_entry;
         finish_entry;
       end;
       end;
@@ -3014,6 +3019,7 @@ implementation
                   appendsym_var_with_name_type_offset(list,tabstractnormalvarsym(tosym),symname(sym, false),tabstractvarsym(sym).vardef,offset,flags);
                   appendsym_var_with_name_type_offset(list,tabstractnormalvarsym(tosym),symname(sym, false),tabstractvarsym(sym).vardef,offset,flags);
                 end;
                 end;
               templist.free;
               templist.free;
+              templist := nil;
               exit;
               exit;
             end;
             end;
         end;
         end;
@@ -3033,6 +3039,7 @@ implementation
         append_labelentry_ref(DW_AT_type,def_dwarf_lab(sym.vardef));
         append_labelentry_ref(DW_AT_type,def_dwarf_lab(sym.vardef));
 
 
         templist.free;
         templist.free;
+        templist := nil;
 
 
         finish_entry;
         finish_entry;
       end;
       end;
@@ -3102,6 +3109,7 @@ implementation
         templist.concat(tai_symbol.createname(target_asm.labelprefix+'debug_line0',AT_METADATA,0,voidpointertype));
         templist.concat(tai_symbol.createname(target_asm.labelprefix+'debug_line0',AT_METADATA,0,voidpointertype));
         current_asmdata.asmlists[al_start].insertlist(templist);
         current_asmdata.asmlists[al_start].insertlist(templist);
         templist.free;
         templist.free;
+        templist := nil;
 
 
         { finalize line info if the unit doesn't contain any function/ }
         { finalize line info if the unit doesn't contain any function/ }
         { procedure/init/final code                                    }
         { procedure/init/final code                                    }
@@ -3226,6 +3234,7 @@ implementation
         linelist.concat(tai_symbol.createname(target_asm.labelprefix+'edebug_line0',AT_METADATA,0,voidpointertype));
         linelist.concat(tai_symbol.createname(target_asm.labelprefix+'edebug_line0',AT_METADATA,0,voidpointertype));
 
 
         flist.free;
         flist.free;
+        flist := nil;
       end;
       end;
 
 
 
 

+ 3 - 0
compiler/dbgstabs.pas

@@ -1177,6 +1177,7 @@ implementation
         current_asmdata.asmlists[al_procedures].insertlistbefore(def.procstarttai,templist);
         current_asmdata.asmlists[al_procedures].insertlistbefore(def.procstarttai,templist);
 
 
         templist.free;
         templist.free;
+        templist := nil;
         current_procdef:=prev_procdef;
         current_procdef:=prev_procdef;
       end;
       end;
 
 
@@ -1749,7 +1750,9 @@ implementation
         deftowritelist:=nil;
         deftowritelist:=nil;
 
 
         stabsvarlist.free;
         stabsvarlist.free;
+        stabsvarlist := nil;
         stabstypelist.free;
         stabstypelist.free;
+        stabstypelist := nil;
         current_filepos:=storefilepos;
         current_filepos:=storefilepos;
       end;
       end;
 
 

+ 1 - 0
compiler/entfile.pas

@@ -609,6 +609,7 @@ begin
 {$endif}
 {$endif}
      if fisfile then
      if fisfile then
        f.Free;
        f.Free;
+       f := nil;
      mode:=0;
      mode:=0;
      closed:=true;
      closed:=true;
    end;
    end;

+ 1 - 0
compiler/export.pas

@@ -282,6 +282,7 @@ procedure DoneExport;
 begin
 begin
   if assigned(Exportlib) then
   if assigned(Exportlib) then
     Exportlib.free;
     Exportlib.free;
+    Exportlib := nil;
 end;
 end;
 
 
 
 

+ 1 - 0
compiler/expunix.pas

@@ -75,6 +75,7 @@ end;
 destructor texportlibunix.destroy;
 destructor texportlibunix.destroy;
 begin
 begin
   fexportedsymnames.free;
   fexportedsymnames.free;
+  fexportedsymnames := nil;
   inherited destroy;
   inherited destroy;
 end;
 end;
 
 

+ 2 - 1
compiler/finput.pas

@@ -500,6 +500,7 @@ uses
         fileclose:=false;
         fileclose:=false;
         try
         try
           f.Free;
           f.Free;
+          f := nil;
           fileclose:=true;
           fileclose:=true;
         except
         except
         end;
         end;
@@ -526,7 +527,7 @@ uses
          ifile : SizeInt;
          ifile : SizeInt;
       begin
       begin
          for ifile:=0 to nfiles-1 do
          for ifile:=0 to nfiles-1 do
-          files[ifile].free;
+          FreeAndNil(files[ifile]);
          FreeMem(files);
          FreeMem(files);
       end;
       end;
 
 

+ 55 - 6
compiler/fmodule.pas

@@ -463,6 +463,7 @@ implementation
            get:=p.data;
            get:=p.data;
            m:=p.needlink;
            m:=p.needlink;
            p.free;
            p.free;
+           p := nil;
          end;
          end;
       end;
       end;
 
 
@@ -483,6 +484,7 @@ implementation
           getusemask:=p.data;
           getusemask:=p.data;
           found:=(p.needlink and mask)<>0;
           found:=(p.needlink and mask)<>0;
           p.free;
           p.free;
+          p := nil;
         until found;
         until found;
       end;
       end;
 
 
@@ -694,25 +696,25 @@ implementation
           end;
           end;
         derefmap:=nil;
         derefmap:=nil;
         if assigned(_exports) then
         if assigned(_exports) then
-         _exports.free;
+          freeandnil(_exports);
         if assigned(dllscannerinputlist) then
         if assigned(dllscannerinputlist) then
-         dllscannerinputlist.free;
+          freeandnil(dllscannerinputlist);
         if assigned(localnamespacelist) then
         if assigned(localnamespacelist) then
-         localnamespacelist.free;
+          freeandnil(localnamespacelist);
         if assigned(scanner) then
         if assigned(scanner) then
-         begin
+          begin
             { also update current_scanner if it was pointing
             { also update current_scanner if it was pointing
               to this module }
               to this module }
             if current_scanner=tscannerfile(scanner) then
             if current_scanner=tscannerfile(scanner) then
               set_current_scanner(nil);
               set_current_scanner(nil);
             freeandnil(scanner);
             freeandnil(scanner);
-
-         end;
+          end;
         if assigned(asmdata) then
         if assigned(asmdata) then
           begin
           begin
             if current_asmdata=asmdata then
             if current_asmdata=asmdata then
               current_asmdata:=nil;
               current_asmdata:=nil;
              asmdata.free;
              asmdata.free;
+             asmdata := nil;
           end;
           end;
         if assigned(procinfo) then
         if assigned(procinfo) then
           begin
           begin
@@ -729,40 +731,68 @@ implementation
           end;
           end;
         DoneDebugInfo(self,current_debuginfo_reset);
         DoneDebugInfo(self,current_debuginfo_reset);
         used_units.free;
         used_units.free;
+        used_units := nil;
         dependent_units.free;
         dependent_units.free;
+        dependent_units := nil;
         resourcefiles.Free;
         resourcefiles.Free;
+        resourcefiles := nil;
         linkorderedsymbols.Free;
         linkorderedsymbols.Free;
+        linkorderedsymbols := nil;
         linkunitofiles.Free;
         linkunitofiles.Free;
+        linkunitofiles := nil;
         linkunitstaticlibs.Free;
         linkunitstaticlibs.Free;
+        linkunitstaticlibs := nil;
         linkunitsharedlibs.Free;
         linkunitsharedlibs.Free;
+        linkunitsharedlibs := nil;
         linkotherofiles.Free;
         linkotherofiles.Free;
+        linkotherofiles := nil;
         linkotherstaticlibs.Free;
         linkotherstaticlibs.Free;
+        linkotherstaticlibs := nil;
         linkothersharedlibs.Free;
         linkothersharedlibs.Free;
+        linkothersharedlibs := nil;
         linkotherframeworks.Free;
         linkotherframeworks.Free;
+        linkotherframeworks := nil;
         stringdispose(mainname);
         stringdispose(mainname);
         externasmsyms.Free;
         externasmsyms.Free;
+        externasmsyms := nil;
         publicasmsyms.Free;
         publicasmsyms.Free;
+        publicasmsyms := nil;
         unitimportsyms.Free;
         unitimportsyms.Free;
+        unitimportsyms := nil;
         FImportLibraryList.Free;
         FImportLibraryList.Free;
+        FImportLibraryList := nil;
         extendeddefs.Free;
         extendeddefs.Free;
+        extendeddefs := nil;
         genericdummysyms.free;
         genericdummysyms.free;
+        genericdummysyms := nil;
         pendingspecializations.free;
         pendingspecializations.free;
+        pendingspecializations := nil;
         waitingforunit.free;
         waitingforunit.free;
+        waitingforunit := nil;
         waitingunits.free;
         waitingunits.free;
+        waitingunits := nil;
         used_rtti_attrs.free;
         used_rtti_attrs.free;
+        used_rtti_attrs := nil;
         stringdispose(asmprefix);
         stringdispose(asmprefix);
         stringdispose(deprecatedmsg);
         stringdispose(deprecatedmsg);
         stringdispose(namespace);
         stringdispose(namespace);
         tcinitcode.free;
         tcinitcode.free;
+        tcinitcode := nil;
         localunitsearchpath.Free;
         localunitsearchpath.Free;
+        localunitsearchpath := nil;
         localobjectsearchpath.free;
         localobjectsearchpath.free;
+        localobjectsearchpath := nil;
         localincludesearchpath.free;
         localincludesearchpath.free;
+        localincludesearchpath := nil;
         locallibrarysearchpath.free;
         locallibrarysearchpath.free;
+        locallibrarysearchpath := nil;
         localframeworksearchpath.free;
         localframeworksearchpath.free;
+        localframeworksearchpath := nil;
 {$ifdef MEMDEBUG}
 {$ifdef MEMDEBUG}
         memsymtable.start;
         memsymtable.start;
 {$endif}
 {$endif}
         derefdata.free;
         derefdata.free;
+        derefdata := nil;
         if assigned(deflist) then
         if assigned(deflist) then
           begin
           begin
             for i:=0 to deflist.Count-1 do
             for i:=0 to deflist.Count-1 do
@@ -770,27 +800,45 @@ implementation
                  (tdef(deflist[i]).registered_in_module=self) then
                  (tdef(deflist[i]).registered_in_module=self) then
                 tdef(deflist[i]).registered_in_module:=nil;
                 tdef(deflist[i]).registered_in_module:=nil;
             deflist.free;
             deflist.free;
+            deflist := nil;
           end;
           end;
         symlist.free;
         symlist.free;
+        symlist := nil;
         ptrdefs.free;
         ptrdefs.free;
+        ptrdefs := nil;
         arraydefs.free;
         arraydefs.free;
+        arraydefs := nil;
         procaddrdefs.free;
         procaddrdefs.free;
+        procaddrdefs := nil;
 {$ifdef llvm}
 {$ifdef llvm}
         llvmdefs.free;
         llvmdefs.free;
+        llvmdefs := nil;
         llvmusedsyms.free;
         llvmusedsyms.free;
+        llvmusedsyms := nil;
         llvmcompilerusedsyms.free;
         llvmcompilerusedsyms.free;
+        llvmcompilerusedsyms := nil;
         llvminitprocs.free;
         llvminitprocs.free;
+        llvminitprocs := nil;
         llvmfiniprocs.free;
         llvmfiniprocs.free;
+        llvmfiniprocs := nil;
         llvmmetadatastrings.free;
         llvmmetadatastrings.free;
+        llvmmetadatastrings := nil;
 {$endif llvm}
 {$endif llvm}
         ansistrdef:=nil;
         ansistrdef:=nil;
         wpoinfo.free;
         wpoinfo.free;
+        wpoinfo := nil;
         checkforwarddefs.free;
         checkforwarddefs.free;
+        checkforwarddefs := nil;
         forwardgenericdefs.free;
         forwardgenericdefs.free;
+        forwardgenericdefs := nil;
         globalsymtable.free;
         globalsymtable.free;
+        globalsymtable := nil;
         localsymtable.free;
         localsymtable.free;
+        localsymtable := nil;
         globalmacrosymtable.free;
         globalmacrosymtable.free;
+        globalmacrosymtable := nil;
         localmacrosymtable.free;
         localmacrosymtable.free;
+        localmacrosymtable := nil;
 {$ifdef MEMDEBUG}
 {$ifdef MEMDEBUG}
         memsymtable.stop;
         memsymtable.stop;
 {$endif}
 {$endif}
@@ -1457,6 +1505,7 @@ initialization
 finalization
 finalization
 {$ifdef MEMDEBUG}
 {$ifdef MEMDEBUG}
   memsymtable.free;
   memsymtable.free;
+  memsymtable := nil;
 {$endif MEMDEBUG}
 {$endif MEMDEBUG}
 
 
 end.
 end.

+ 2 - 0
compiler/fpcp.pas

@@ -312,6 +312,7 @@ implementation
           rewriteppu(module^.module.ppufilename,stream);
           rewriteppu(module^.module.ppufilename,stream);
           module^.size:=stream.position;
           module^.size:=stream.position;
           stream.free;
           stream.free;
+          stream := nil;
         end;
         end;
 
 
       pos:=pcpfile.position;
       pos:=pcpfile.position;
@@ -416,6 +417,7 @@ implementation
   destructor tpcppackage.destroy;
   destructor tpcppackage.destroy;
     begin
     begin
       pcpfile.free;
       pcpfile.free;
+      pcpfile := nil;
       inherited destroy;
       inherited destroy;
     end;
     end;
 
 

+ 4 - 1
compiler/fpkg.pas

@@ -26,6 +26,7 @@ unit fpkg;
 interface
 interface
 
 
   uses
   uses
+    sysutils,
     cclasses,
     cclasses,
     globtype,
     globtype,
     finput;
     finput;
@@ -87,7 +88,9 @@ implementation
             dispose(p);
             dispose(p);
           end;
           end;
       containedmodules.free;
       containedmodules.free;
+      containedmodules := nil;
       requiredpackages.free;
       requiredpackages.free;
+      requiredpackages := nil;
       inherited destroy;
       inherited destroy;
     end;
     end;
 
 
@@ -108,7 +111,7 @@ implementation
             for i:=0 to packagelist.count-1 do
             for i:=0 to packagelist.count-1 do
               begin
               begin
                 pkgentry:=ppackageentry(packagelist[i]);
                 pkgentry:=ppackageentry(packagelist[i]);
-                pkgentry^.package.free;
+                FreeAndNil(pkgentry^.package);
                 dispose(pkgentry);
                 dispose(pkgentry);
               end;
               end;
           end;
           end;

+ 1 - 0
compiler/fppu.pas

@@ -2530,6 +2530,7 @@ var
                       end;
                       end;
                     finally
                     finally
                       Cycle.Free;
                       Cycle.Free;
+                      Cycle := nil;
                     end;
                     end;
                     if assigned(hp2) then
                     if assigned(hp2) then
                       Message2(unit_f_circular_unit_reference,callermodule.realmodulename^,hp.realmodulename^);
                       Message2(unit_f_circular_unit_reference,callermodule.realmodulename^,hp.realmodulename^);

+ 2 - 0
compiler/gendef.pas

@@ -73,7 +73,9 @@ begin
      ([cs_link_nolink,cs_link_deffile]*current_settings.globalswitches=[]) then
      ([cs_link_nolink,cs_link_deffile]*current_settings.globalswitches=[]) then
     DeleteFile(FName);
     DeleteFile(FName);
   importlist.Free;
   importlist.Free;
+  importlist := nil;
   exportlist.Free;
   exportlist.Free;
+  exportlist := nil;
 end;
 end;
 
 
 
 

+ 10 - 0
compiler/globals.pas

@@ -1705,15 +1705,25 @@ implementation
      begin
      begin
        calldoneprocs;
        calldoneprocs;
        librarysearchpath.Free;
        librarysearchpath.Free;
+       librarysearchpath := nil;
        unitsearchpath.Free;
        unitsearchpath.Free;
+       unitsearchpath := nil;
        objectsearchpath.Free;
        objectsearchpath.Free;
+       objectsearchpath := nil;
        includesearchpath.Free;
        includesearchpath.Free;
+       includesearchpath := nil;
        frameworksearchpath.Free;
        frameworksearchpath.Free;
+       frameworksearchpath := nil;
        LinkLibraryAliases.Free;
        LinkLibraryAliases.Free;
+       LinkLibraryAliases := nil;
        LinkLibraryOrder.Free;
        LinkLibraryOrder.Free;
+       LinkLibraryOrder := nil;
        packagesearchpath.Free;
        packagesearchpath.Free;
+       packagesearchpath := nil;
        namespacelist.Free;
        namespacelist.Free;
+       namespacelist := nil;
        premodule_namespacelist.Free;
        premodule_namespacelist.Free;
+       premodule_namespacelist := nil;
        current_namespacelist:=Nil;
        current_namespacelist:=Nil;
      end;
      end;
 
 

+ 16 - 3
compiler/htypechk.pas

@@ -26,7 +26,7 @@ unit htypechk;
 interface
 interface
 
 
     uses
     uses
-      cclasses,cmsgs,tokens,
+      sysutils,cclasses,cmsgs,tokens,
       node,globtype,compinnr,
       node,globtype,compinnr,
       symconst,symtype,symdef,symsym,symbase,
       symconst,symtype,symdef,symsym,symbase,
       pgentype;
       pgentype;
@@ -807,6 +807,7 @@ implementation
           begin
           begin
             candidates.done;
             candidates.done;
             ppn.free;
             ppn.free;
+            ppn := nil;
             if not (ocf_check_only in ocf) then
             if not (ocf_check_only in ocf) then
               begin
               begin
                 CGMessage2(parser_e_operator_not_overloaded_2,ld.typename,arraytokeninfo[optoken].str);
                 CGMessage2(parser_e_operator_not_overloaded_2,ld.typename,arraytokeninfo[optoken].str);
@@ -828,6 +829,7 @@ implementation
           begin
           begin
             candidates.done;
             candidates.done;
             ppn.free;
             ppn.free;
+            ppn := nil;
             if not (ocf_check_only in ocf) then
             if not (ocf_check_only in ocf) then
               begin
               begin
                 CGMessage2(parser_e_operator_not_overloaded_2,ld.typename,arraytokeninfo[optoken].str);
                 CGMessage2(parser_e_operator_not_overloaded_2,ld.typename,arraytokeninfo[optoken].str);
@@ -853,6 +855,7 @@ implementation
         if ocf_check_only in ocf then
         if ocf_check_only in ocf then
           begin
           begin
             ppn.free;
             ppn.free;
+            ppn := nil;
             result:=true;
             result:=true;
             exit;
             exit;
           end;
           end;
@@ -1005,6 +1008,7 @@ implementation
         if (cand_cnt=0) then
         if (cand_cnt=0) then
           begin
           begin
             ppn.free;
             ppn.free;
+            ppn := nil;
             if not (ocf_check_only in ocf) then
             if not (ocf_check_only in ocf) then
               t:=cnothingnode.create;
               t:=cnothingnode.create;
             exit;
             exit;
@@ -1013,6 +1017,7 @@ implementation
         if ocf_check_only in ocf then
         if ocf_check_only in ocf then
           begin
           begin
             ppn.free;
             ppn.free;
+            ppn := nil;
             result:=true;
             result:=true;
             exit;
             exit;
           end;
           end;
@@ -1431,6 +1436,7 @@ implementation
                   for i:=0 to typeconvs.Count-1 do
                   for i:=0 to typeconvs.Count-1 do
                     ttypeconvnode(typeconvs[i]).assignment_side:=false;
                     ttypeconvnode(typeconvs[i]).assignment_side:=false;
                 typeconvs.free;
                 typeconvs.free;
+                typeconvs := nil;
               end;
               end;
           end;
           end;
 
 
@@ -2209,6 +2215,7 @@ implementation
         sym : tsym;
         sym : tsym;
       begin
       begin
         FIgnoredCandidateProcs.free;
         FIgnoredCandidateProcs.free;
+        FIgnoredCandidateProcs := nil;
         { free any symbols for anonymous parameter types that we're used for
         { free any symbols for anonymous parameter types that we're used for
           specialization when no specialization was picked }
           specialization when no specialization was picked }
         TFPList.FreeAndNilObjects(FParaAnonSyms);
         TFPList.FreeAndNilObjects(FParaAnonSyms);
@@ -2229,7 +2236,7 @@ implementation
                        break;
                        break;
                      end;
                      end;
                  end;
                  end;
-               hp^.data.free;
+               FreeAndNil(hp^.data);
              end;
              end;
            dispose(hp);
            dispose(hp);
            hp:=hpnext;
            hp:=hpnext;
@@ -2675,6 +2682,7 @@ implementation
                 if tprocsym(pd.procsym).procdeflist.extract(pd)<>pd then
                 if tprocsym(pd.procsym).procdeflist.extract(pd)<>pd then
                   internalerror(20150828);
                   internalerror(20150828);
                 pd.free;
                 pd.free;
+                pd := nil;
               end;
               end;
           end;
           end;
 {$ifndef DISABLE_FAST_OVERLOAD_PATCH}
 {$ifndef DISABLE_FAST_OVERLOAD_PATCH}
@@ -2689,6 +2697,7 @@ implementation
         calc_distance(st,flags);
         calc_distance(st,flags);
 
 
         ProcdefOverloadList.Free;
         ProcdefOverloadList.Free;
+        ProcdefOverloadList := nil;
       end;
       end;
 
 
 
 
@@ -3100,6 +3109,7 @@ implementation
                    eq:=compare_defs_ext(n.resultdef,def_to,n.nodetype,convtype,pdoper,cdoptions);
                    eq:=compare_defs_ext(n.resultdef,def_to,n.nodetype,convtype,pdoper,cdoptions);
                    check_valid_var:=false;
                    check_valid_var:=false;
                    n.free;
                    n.free;
+                   n := nil;
                  end
                  end
               else if is_open_array(def_to) and
               else if is_open_array(def_to) and
                       is_class_or_interface_or_dispinterface_or_objc_or_java(tarraydef(def_to).elementdef) and
                       is_class_or_interface_or_dispinterface_or_objc_or_java(tarraydef(def_to).elementdef) and
@@ -3201,7 +3211,10 @@ implementation
 
 
               { maybe release temp currpt }
               { maybe release temp currpt }
               if releasecurrpt then
               if releasecurrpt then
-                currpt.free;
+               begin
+                 currpt.free;
+                 currpt := nil;
+               end;
 
 
               { next parameter in the call tree }
               { next parameter in the call tree }
               pt:=tcallparanode(pt.right);
               pt:=tcallparanode(pt.right);

+ 1 - 0
compiler/import.pas

@@ -122,6 +122,7 @@ procedure DoneImport;
 begin
 begin
   if assigned(importlib) then
   if assigned(importlib) then
     importlib.free;
     importlib.free;
+    importlib := nil;
 end;
 end;
 
 
 end.
 end.

+ 23 - 2
compiler/link.pas

@@ -199,6 +199,7 @@ Implementation
         if CStreamError<>0 then
         if CStreamError<>0 then
           begin
           begin
             fs.Free;
             fs.Free;
+            fs := nil;
             Comment(V_Error,'Can''t open file: '+fn);
             Comment(V_Error,'Can''t open file: '+fn);
             exit;
             exit;
           end;
           end;
@@ -209,6 +210,7 @@ Implementation
         until bufcount<bufsize;
         until bufcount<bufsize;
         buf:=nil;
         buf:=nil;
         fs.Free;
         fs.Free;
+        fs := nil;
       end;
       end;
 
 
 
 
@@ -376,10 +378,15 @@ Implementation
     Destructor TLinker.Destroy;
     Destructor TLinker.Destroy;
       begin
       begin
         ObjectFiles.Free;
         ObjectFiles.Free;
+        ObjectFiles := nil;
         SharedLibFiles.Free;
         SharedLibFiles.Free;
+        SharedLibFiles := nil;
         StaticLibFiles.Free;
         StaticLibFiles.Free;
+        StaticLibFiles := nil;
         FrameworkFiles.Free;
         FrameworkFiles.Free;
+        FrameworkFiles := nil;
         OrderedSymbols.Free;
         OrderedSymbols.Free;
+        OrderedSymbols := nil;
         inherited;
         inherited;
       end;
       end;
 
 
@@ -638,6 +645,7 @@ Implementation
         for i:=0 to p.count-1 do
         for i:=0 to p.count-1 do
           src.insert(p[i].Key);
           src.insert(p[i].Key);
         p.free;
         p.free;
+        p := nil;
       end;
       end;
 
 
 
 
@@ -677,6 +685,7 @@ Implementation
         symfile.WriteToDisk;
         symfile.WriteToDisk;
         result:=symfile.fn;
         result:=symfile.fn;
         symfile.Free;
         symfile.Free;
+        symfile := nil;
       end;
       end;
 
 
 
 
@@ -770,6 +779,7 @@ Implementation
         if result then
         if result then
           ObjectFiles.concatList(sanitizerlibraryfiles);
           ObjectFiles.concatList(sanitizerlibraryfiles);
         sanitizerlibraryfiles.free;
         sanitizerlibraryfiles.free;
+        sanitizerlibraryfiles := nil;
       end;
       end;
 
 
 
 
@@ -1543,9 +1553,13 @@ Implementation
     Destructor TInternalLinker.Destroy;
     Destructor TInternalLinker.Destroy;
       begin
       begin
         FGroupStack.Free;
         FGroupStack.Free;
+        FGroupStack := nil;
         linkscript.free;
         linkscript.free;
-        StaticLibraryList.Free;
-        ImportLibraryList.Free;
+        linkscript := nil;
+        FStaticLibraryList.Free;
+        FStaticLibraryList := nil;
+        FImportLibraryList.Free;
+        FImportLibraryList := nil;
         if assigned(IsHandled) then
         if assigned(IsHandled) then
           begin
           begin
             IsHandled:=nil;
             IsHandled:=nil;
@@ -1710,7 +1724,9 @@ Implementation
           end;
           end;
         { release input object }
         { release input object }
         objinput.free;
         objinput.free;
+        objinput := nil;
         objreader.free;
         objreader.free;
+        objreader := nil;
       end;
       end;
 
 
 
 
@@ -1744,7 +1760,9 @@ Implementation
                   TFPObjectList(FGroupStack.Last).Add(stmt);
                   TFPObjectList(FGroupStack.Last).Add(stmt);
                 end;
                 end;
               objinput.Free;
               objinput.Free;
+              objinput := nil;
               objreader.Free;
               objreader.Free;
+              objreader := nil;
             end
             end
           else       { try parsing as script }
           else       { try parsing as script }
             begin
             begin
@@ -1752,7 +1770,9 @@ Implementation
               ScriptLexer:=TScriptLexer.Create(objreader);
               ScriptLexer:=TScriptLexer.Create(objreader);
               ParseLdScript(ScriptLexer);
               ParseLdScript(ScriptLexer);
               ScriptLexer.Free;
               ScriptLexer.Free;
+              ScriptLexer := nil;
               objreader.Free;
               objreader.Free;
+              objreader := nil;
             end;
             end;
       end;
       end;
 
 
@@ -2244,6 +2264,7 @@ Implementation
       begin
       begin
         if assigned(linker) then
         if assigned(linker) then
          Linker.Free;
          Linker.Free;
+         Linker := nil;
       end;
       end;
 
 
 
 

+ 2 - 0
compiler/machoutils.pas

@@ -543,6 +543,7 @@ const
         begin
         begin
           if AllowFreeWriter then
           if AllowFreeWriter then
             ARawWriter.Free;
             ARawWriter.Free;
+            ARawWriter := nil;
           Result:=nil;
           Result:=nil;
         end;
         end;
       end;
       end;
@@ -587,6 +588,7 @@ const
     begin
     begin
       if fown then
       if fown then
         fwriter.Free;
         fwriter.Free;
+        fwriter := nil;
       inherited Destroy;
       inherited Destroy;
     end;
     end;
 
 

+ 1 - 1
compiler/nadd.pas

@@ -913,7 +913,7 @@ const
               have a side effect }
               have a side effect }
             if (is_constintnode(left) and might_have_sideeffects(right)) or
             if (is_constintnode(left) and might_have_sideeffects(right)) or
               (is_constintnode(right) and might_have_sideeffects(left)) then
               (is_constintnode(right) and might_have_sideeffects(left)) then
-              t.free
+              t.free // no nil needed
             else
             else
               result:=t;
               result:=t;
             exit;
             exit;

+ 7 - 3
compiler/nbas.pas

@@ -863,6 +863,7 @@ implementation
                                 Flags := Flags + (p.left.flags * [nf_usercode_entry]);
                                 Flags := Flags + (p.left.flags * [nf_usercode_entry]);
 
 
                                 p.Free;
                                 p.Free;
+                                p := nil;
                                 Continue;
                                 Continue;
                               end;
                               end;
                           else
                           else
@@ -1032,7 +1033,10 @@ implementation
     destructor tasmnode.destroy;
     destructor tasmnode.destroy;
       begin
       begin
         if assigned(p_asm) then
         if assigned(p_asm) then
-          p_asm.free;
+          begin
+            p_asm.free;
+            p_asm := nil;
+          end;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -1826,8 +1830,8 @@ implementation
 
 
     destructor ttempdeletenode.destroy;
     destructor ttempdeletenode.destroy;
       begin
       begin
-        tempinfo^.withnode.free;
-        tempinfo^.tempinitcode.free;
+        tempinfo^.withnode.free; // no nil needed
+        tempinfo^.tempinitcode.free; // no nil needed
         dispose(tempinfo);
         dispose(tempinfo);
         inherited destroy;
         inherited destroy;
       end;
       end;

+ 25 - 1
compiler/ncal.pas

@@ -582,6 +582,7 @@ implementation
 
 
         { old argument list skeleton isn't needed anymore }
         { old argument list skeleton isn't needed anymore }
         parametersnode.free;
         parametersnode.free;
+        parametersnode := nil;
 
 
         pvardatadef:=tpointerdef(search_system_type('PVARDATA').typedef);
         pvardatadef:=tpointerdef(search_system_type('PVARDATA').typedef);
 
 
@@ -614,6 +615,7 @@ implementation
           )
           )
         );
         );
         tcb.free;
         tcb.free;
+        tcb := nil;
 
 
         if variantdispatch then
         if variantdispatch then
           begin
           begin
@@ -971,7 +973,9 @@ implementation
 
 
       begin
       begin
          fparainit.free;
          fparainit.free;
+         fparainit := nil;
          fparacopyback.free;
          fparacopyback.free;
+         fparacopyback := nil;
          inherited destroy;
          inherited destroy;
       end;
       end;
 
 
@@ -1181,6 +1185,7 @@ implementation
                  left:=ttypeconvnode(left).left;
                  left:=ttypeconvnode(left).left;
                  ttypeconvnode(hp).left:=nil;
                  ttypeconvnode(hp).left:=nil;
                  hp.free;
                  hp.free;
+                 hp := nil;
                end;
                end;
              maybe_global_proc_to_nested(left,parasym.vardef);
              maybe_global_proc_to_nested(left,parasym.vardef);
 
 
@@ -1726,15 +1731,26 @@ implementation
     destructor tcallnode.destroy;
     destructor tcallnode.destroy;
       begin
       begin
          methodpointer.free;
          methodpointer.free;
+         methodpointer := nil;
          callinitblock.free;
          callinitblock.free;
+         callinitblock := nil;
          callcleanupblock.free;
          callcleanupblock.free;
+         callcleanupblock := nil;
          funcretnode.free;
          funcretnode.free;
+         funcretnode := nil;
          if assigned(varargsparas) then
          if assigned(varargsparas) then
+         begin
            varargsparas.free;
            varargsparas.free;
+           varargsparas := nil;
+         end;
          call_self_node.free;
          call_self_node.free;
+         call_self_node := nil;
          call_vmt_node.free;
          call_vmt_node.free;
+         call_vmt_node := nil;
          vmt_entry.free;
          vmt_entry.free;
+         vmt_entry := nil;
          spezcontext.free;
          spezcontext.free;
+         spezcontext := nil;
          inherited destroy;
          inherited destroy;
       end;
       end;
 
 
@@ -2396,6 +2412,7 @@ implementation
                         p:=left;
                         p:=left;
                         Tcallparanode(tinlinenode(temp).left).left:=nil;
                         Tcallparanode(tinlinenode(temp).left).left:=nil;
                         temp.free;
                         temp.free;
+                        temp := nil;
 
 
                         typecheckpass(hightree);
                         typecheckpass(hightree);
                       end
                       end
@@ -2425,6 +2442,7 @@ implementation
                           right:=nil;
                           right:=nil;
                         end;
                         end;
                       temp.free;
                       temp.free;
+                      temp := nil;
 
 
                       {Tree changed from p[l..h] to p[l], recalculate resultdef.}
                       {Tree changed from p[l..h] to p[l], recalculate resultdef.}
                       p.resultdef:=nil;
                       p.resultdef:=nil;
@@ -2446,6 +2464,7 @@ implementation
                         end
                         end
                       else
                       else
                         temp.free;
                         temp.free;
+                        temp := nil;
                     end;
                     end;
                 end;
                 end;
             end;
             end;
@@ -3764,6 +3783,7 @@ implementation
           end;
           end;
         if assigned(parents) then
         if assigned(parents) then
           parents.free;
           parents.free;
+          parents := nil;
         { Finally give out a warning for each abstract method still in the list }
         { Finally give out a warning for each abstract method still in the list }
         for i:=0 to AbstractMethodsList.Count-1 do
         for i:=0 to AbstractMethodsList.Count-1 do
           begin
           begin
@@ -3775,7 +3795,10 @@ implementation
               end;
               end;
           end;
           end;
         if assigned(AbstractMethodsList) then
         if assigned(AbstractMethodsList) then
-          AbstractMethodsList.Free;
+          begin
+            AbstractMethodsList.Free;
+            AbstractMethodsList := nil;
+          end;
       end;
       end;
 
 
 
 
@@ -5746,6 +5769,7 @@ implementation
         if assigned(n) then
         if assigned(n) then
           begin
           begin
             inlineblock.free;
             inlineblock.free;
+            inlineblock := nil;
             result:=n;
             result:=n;
           end;
           end;
 
 

+ 3 - 0
compiler/ncgcon.pas

@@ -363,6 +363,7 @@ implementation
                         internalerror(2013120103);
                         internalerror(2013120103);
                    end;
                    end;
                    datatcb.free;
                    datatcb.free;
+                   datatcb := nil;
                    lab_str:=lastlabel.lab;
                    lab_str:=lastlabel.lab;
                    entry^.Data:=lastlabel.lab;
                    entry^.Data:=lastlabel.lab;
                 end;
                 end;
@@ -420,6 +421,7 @@ implementation
         current_asmdata.asmlists[al_typedconsts].concatlist(tcb.get_final_asmlist(
         current_asmdata.asmlists[al_typedconsts].concatlist(tcb.get_final_asmlist(
           result,resultdef,sec_rodata_norel,result.name,const_align(8)));
           result,resultdef,sec_rodata_norel,result.name,const_align(8)));
         tcb.free;
         tcb.free;
+        tcb := nil;
       end;
       end;
 
 
 
 
@@ -515,6 +517,7 @@ implementation
                  current_asmdata.asmlists[al_typedconsts].concatList(
                  current_asmdata.asmlists[al_typedconsts].concatList(
                    datatcb.get_final_asmlist(lastlabel,rec_tguid,sec_rodata_norel,lastlabel.name,const_align(16)));
                    datatcb.get_final_asmlist(lastlabel,rec_tguid,sec_rodata_norel,lastlabel.name,const_align(16)));
                  datatcb.free;
                  datatcb.free;
+                 datatcb := nil;
                  lab_set:=lastlabel;
                  lab_set:=lastlabel;
                  entry^.Data:=lastlabel;
                  entry^.Data:=lastlabel;
                end;
                end;

+ 3 - 0
compiler/ncgflw.pas

@@ -371,8 +371,10 @@ implementation
              { add all lists together }
              { add all lists together }
              org_list.concatlist(then_list);
              org_list.concatlist(then_list);
              then_list.free;
              then_list.free;
+             then_list := nil;
              org_list.concatlist(else_list);
              org_list.concatlist(else_list);
              else_list.free;
              else_list.free;
+             else_list := nil;
              org_list.concatlist(current_asmdata.CurrAsmList);
              org_list.concatlist(current_asmdata.CurrAsmList);
              current_asmdata.CurrAsmList.free;
              current_asmdata.CurrAsmList.free;
              current_asmdata.CurrAsmList := org_list;
              current_asmdata.CurrAsmList := org_list;
@@ -1009,6 +1011,7 @@ implementation
 
 
              current_asmdata.CurrAsmList.concatList(tmplist);
              current_asmdata.CurrAsmList.concatList(tmplist);
              tmplist.free;
              tmplist.free;
+             tmplist := nil;
            end
            end
          else
          else
            cexceptionstatehandler.emit_except_label(current_asmdata.CurrAsmList,exceptframekind,finallyexceptionstate,excepttemps);
            cexceptionstatehandler.emit_except_label(current_asmdata.CurrAsmList,exceptframekind,finallyexceptionstate,excepttemps);

+ 16 - 0
compiler/ncgrtti.pas

@@ -485,6 +485,7 @@ implementation
             );
             );
 
 
             loctcb.free;
             loctcb.free;
+            loctcb := nil;
 
 
             entry^.data:=loclab;
             entry^.data:=loclab;
           end
           end
@@ -638,6 +639,7 @@ implementation
             tcb.emit_tai(tai_const.Create_sym(tbllbl),voidpointertype);
             tcb.emit_tai(tai_const.Create_sym(tbllbl),voidpointertype);
           end;
           end;
         list.free;
         list.free;
+        list := nil;
       end;
       end;
 
 
 
 
@@ -725,6 +727,7 @@ implementation
             maybe_add_comment(tcb,'RTTI end field '+tostr(i)+': '+sym.prettyname);
             maybe_add_comment(tcb,'RTTI end field '+tostr(i)+': '+sym.prettyname);
           end;
           end;
         fields.free;
         fields.free;
+        fields := nil;
       end;
       end;
 
 
 
 
@@ -885,6 +888,7 @@ implementation
           end;
           end;
         tcb.end_anonymous_record;
         tcb.end_anonymous_record;
         list.free;
         list.free;
+        list := nil;
       end;
       end;
 
 
 
 
@@ -1226,6 +1230,7 @@ implementation
                       tbltcb.get_final_asmlist(tbllab,tbldef,sec_rodata,tbllab.name,const_align(sizeof(pint)))
                       tbltcb.get_final_asmlist(tbllab,tbldef,sec_rodata,tbllab.name,const_align(sizeof(pint)))
                     );
                     );
                     tbltcb.free;
                     tbltcb.free;
+                    tbltcb := nil;
                     { write the pointer to the prop info }
                     { write the pointer to the prop info }
                     maybe_add_comment(tcb,#9'property info reference');
                     maybe_add_comment(tcb,#9'property info reference');
                     tcb.emit_tai(Tai_const.Create_sym(tbllab),voidpointertype);
                     tcb.emit_tai(Tai_const.Create_sym(tbllab),voidpointertype);
@@ -1720,6 +1725,7 @@ implementation
               tcb.get_final_asmlist(rttilab,rttidef,sec_rodata,rttilab.name,
               tcb.get_final_asmlist(rttilab,rttidef,sec_rodata,rttilab.name,
               sizeof(PInt)));
               sizeof(PInt)));
             tcb.free;
             tcb.free;
+            tcb := nil;
           end;
           end;
 
 
 
 
@@ -1733,6 +1739,7 @@ implementation
             collect_propnamelist(propnamelist,def,visibilities);
             collect_propnamelist(propnamelist,def,visibilities);
             properties_write_rtti_data(tcb,propnamelist,def.symtable,true,visibilities);
             properties_write_rtti_data(tcb,propnamelist,def.symtable,true,visibilities);
             propnamelist.free;
             propnamelist.free;
+            propnamelist := nil;
           end;
           end;
 
 
         var
         var
@@ -1968,6 +1975,7 @@ implementation
             collect_propnamelist(propnamelist,def,visibilities);
             collect_propnamelist(propnamelist,def,visibilities);
             properties_write_rtti_data(tcb,propnamelist,def.symtable,true,visibilities);
             properties_write_rtti_data(tcb,propnamelist,def.symtable,true,visibilities);
             propnamelist.free;
             propnamelist.free;
+            propnamelist := nil;
           end;
           end;
 
 
           procedure objectdef_rtti_class_full(def:tobjectdef);
           procedure objectdef_rtti_class_full(def:tobjectdef);
@@ -2024,6 +2032,7 @@ implementation
             tcb.end_anonymous_record;
             tcb.end_anonymous_record;
 
 
             propnamelist.free;
             propnamelist.free;
+            propnamelist := nil;
           end;
           end;
 
 
           procedure objectdef_rtti_interface_full(def:tobjectdef);
           procedure objectdef_rtti_interface_full(def:tobjectdef);
@@ -2089,6 +2098,7 @@ implementation
             tcb.end_anonymous_record;
             tcb.end_anonymous_record;
 
 
             propnamelist.free;
             propnamelist.free;
+            propnamelist := nil;
           end;
           end;
 
 
         begin
         begin
@@ -2234,6 +2244,7 @@ implementation
             );
             );
 
 
             argtcb.free;
             argtcb.free;
+            argtcb := nil;
 
 
             { write argument size and the reference to the argument entry }
             { write argument size and the reference to the argument entry }
             tbltcb.emit_ord_const(argdef.size,u16inttype);
             tbltcb.emit_ord_const(argdef.size,u16inttype);
@@ -2295,6 +2306,7 @@ implementation
       );
       );
 
 
       tbltcb.free;
       tbltcb.free;
+      tbltcb := nil;
 
 
       { write the reference to the attribute table }
       { write the reference to the attribute table }
       tcb.emit_tai(Tai_const.Create_sym(tbllab),voidpointertype);
       tcb.emit_tai(Tai_const.Create_sym(tbllab),voidpointertype);
@@ -2441,6 +2453,7 @@ implementation
               rttilab,tabledef,sec_rodata,
               rttilab,tabledef,sec_rodata,
               rttilab.name,sizeof(PInt)));
               rttilab.name,sizeof(PInt)));
             tcb.free;
             tcb.free;
+            tcb := nil;
 
 
             current_module.add_public_asmsym(rttilab);
             current_module.add_public_asmsym(rttilab);
         end;
         end;
@@ -2487,6 +2500,7 @@ implementation
             rttilab,tabledef,sec_rodata,
             rttilab,tabledef,sec_rodata,
             rttilab.name,sizeof(PInt)));
             rttilab.name,sizeof(PInt)));
           tcb.free;
           tcb.free;
+          tcb := nil;
 
 
           current_module.add_public_asmsym(rttilab);
           current_module.add_public_asmsym(rttilab);
         end;
         end;
@@ -2526,6 +2540,7 @@ implementation
           syms.sort(@enumsym_compare_value);
           syms.sort(@enumsym_compare_value);
           enumdef_rtti_ord2stringindex(rttidef,syms);
           enumdef_rtti_ord2stringindex(rttidef,syms);
           syms.free;
           syms.free;
+          syms := nil;
         end;
         end;
 
 
 
 
@@ -2672,6 +2687,7 @@ implementation
         current_asmdata.AsmLists[al_rtti].concatList(
         current_asmdata.AsmLists[al_rtti].concatList(
           tcb.get_final_asmlist(rttilab,rttidef,sec_rodata,rttilab.name,min(target_info.alignment.maxCrecordalign,SizeOf(QWord))));
           tcb.get_final_asmlist(rttilab,rttidef,sec_rodata,rttilab.name,min(target_info.alignment.maxCrecordalign,SizeOf(QWord))));
         tcb.free;
         tcb.free;
+        tcb := nil;
 
 
         current_module.add_public_asmsym(rttilab);
         current_module.add_public_asmsym(rttilab);
 
 

+ 6 - 0
compiler/ncgvmt.pas

@@ -718,6 +718,7 @@ implementation
           end;
           end;
 
 
         classtablelist.free;
         classtablelist.free;
+        classtablelist := nil;
       end;
       end;
 
 
 
 
@@ -923,6 +924,7 @@ implementation
             s,
             s,
             sizeof(pint)));
             sizeof(pint)));
           tcb.free;
           tcb.free;
+          tcb := nil;
           current_module.add_public_asmsym(sym);
           current_module.add_public_asmsym(sym);
         end;
         end;
       s:=make_mangledname('IIDSTR',_class.owner,_class.objname^);
       s:=make_mangledname('IIDSTR',_class.owner,_class.objname^);
@@ -936,6 +938,7 @@ implementation
         s,
         s,
         sizeof(pint)));
         sizeof(pint)));
       tcb.free;
       tcb.free;
+      tcb := nil;
       current_module.add_public_asmsym(sym);
       current_module.add_public_asmsym(sym);
     end;
     end;
 
 
@@ -1232,6 +1235,7 @@ implementation
            )
            )
          );
          );
          tcb.free;
          tcb.free;
+         tcb := nil;
 {$ifdef vtentry}
 {$ifdef vtentry}
          { write vtinherit symbol to notify the linker of the class inheritance tree }
          { write vtinherit symbol to notify the linker of the class inheritance tree }
          hs:='VTINHERIT'+'_'+_class.vmt_mangledname+'$$';
          hs:='VTINHERIT'+'_'+_class.vmt_mangledname+'$$';
@@ -1325,6 +1329,7 @@ implementation
                            current_debuginfo.insertlineinfo(tmplist);
                            current_debuginfo.insertlineinfo(tmplist);
                       list.concatlist(tmplist);
                       list.concatlist(tmplist);
                       tmplist.Free;
                       tmplist.Free;
+                      tmplist := nil;
                       current_filepos:=oldfileposinfo;
                       current_filepos:=oldfileposinfo;
                     end;
                     end;
                   end;
                   end;
@@ -1365,6 +1370,7 @@ implementation
                       if (oo_has_vmt in tobjectdef(def).objectoptions) then
                       if (oo_has_vmt in tobjectdef(def).objectoptions) then
                         vmtwriter.writevmt;
                         vmtwriter.writevmt;
                       vmtwriter.free;
                       vmtwriter.free;
+                      vmtwriter := nil;
                       include(def.defstates,ds_vmt_written);
                       include(def.defstates,ds_vmt_written);
                     end;
                     end;
                   if is_class(def) then
                   if is_class(def) then

+ 11 - 2
compiler/ncnv.pas

@@ -612,7 +612,9 @@ implementation
                               for l:=tordconstnode(p2).value.svalue to tordconstnode(p3).value.svalue do
                               for l:=tordconstnode(p2).value.svalue to tordconstnode(p3).value.svalue do
                                 do_set(l);
                                 do_set(l);
                               p2.free;
                               p2.free;
+                              p2 := nil;
                               p3.free;
                               p3.free;
+                              p3 := nil;
                             end
                             end
                            else
                            else
                             begin
                             begin
@@ -649,6 +651,7 @@ implementation
 
 
                           do_set(tordconstnode(p2).value.svalue);
                           do_set(tordconstnode(p2).value.svalue);
                           p2.free;
                           p2.free;
+                          p2 := nil;
                         end
                         end
                        else
                        else
                         begin
                         begin
@@ -676,7 +679,7 @@ implementation
               hp:=tarrayconstructornode(tarrayconstructornode(p2).right);
               hp:=tarrayconstructornode(tarrayconstructornode(p2).right);
               tarrayconstructornode(p2).right:=nil;
               tarrayconstructornode(p2).right:=nil;
               if freep then
               if freep then
-                p2.free;
+                p2.free; // no nil needed
               current_filepos:=oldfilepos;
               current_filepos:=oldfilepos;
               first:=false;
               first:=false;
             end;
             end;
@@ -687,7 +690,7 @@ implementation
          begin
          begin
            { empty set [], only remove node }
            { empty set [], only remove node }
            if freep then
            if freep then
-             p.free;
+             p.free; // no nil needed
          end;
          end;
         { set the initial set type }
         { set the initial set type }
         constp.resultdef:=csetdef.create(hdef,constsetlo.svalue,constsethi.svalue,true);
         constp.resultdef:=csetdef.create(hdef,constsetlo.svalue,constsethi.svalue,true);
@@ -895,6 +898,7 @@ implementation
             typecheckpass(fromnode);
             typecheckpass(fromnode);
             ttypeconvnode(hp).left:=nil;
             ttypeconvnode(hp).left:=nil;
             hp.free;
             hp.free;
+            hp := nil;
             result:=true;
             result:=true;
           end;
           end;
       end;
       end;
@@ -929,6 +933,7 @@ implementation
             typecheckpass(fromnode);
             typecheckpass(fromnode);
             ttypeconvnode(hp).left:=nil;
             ttypeconvnode(hp).left:=nil;
             hp.free;
             hp.free;
+            hp := nil;
             result:=true;
             result:=true;
           end;
           end;
       end;
       end;
@@ -2716,6 +2721,7 @@ implementation
             typecheckpass(left);
             typecheckpass(left);
             ttypeconvnode(hp).left:=nil;
             ttypeconvnode(hp).left:=nil;
             hp.free;
             hp.free;
+            hp := nil;
           end;
           end;
 
 
         intfdef:=capturer_add_procvar_or_proc(current_procinfo,left,capturer,hp);
         intfdef:=capturer_add_procvar_or_proc(current_procinfo,left,capturer,hp);
@@ -3481,6 +3487,7 @@ implementation
                       n:=newblock;
                       n:=newblock;
                       do_typecheckpass(n);
                       do_typecheckpass(n);
                       originaldivtree.free;
                       originaldivtree.free;
+                      originaldivtree := nil;
                     end;
                     end;
                 end
                 end
               else
               else
@@ -3618,6 +3625,7 @@ implementation
                   if ([nf_explicit,nf_internal] * flags <> []) then
                   if ([nf_explicit,nf_internal] * flags <> []) then
                     include(result.flags, nf_explicit);
                     include(result.flags, nf_explicit);
                   hp.free;
                   hp.free;
+                  hp := nil;
                 end;
                 end;
             end;
             end;
 
 
@@ -5137,6 +5145,7 @@ implementation
 
 
       begin
       begin
         call.free;
         call.free;
+        call := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 

+ 22 - 1
compiler/nflw.pas

@@ -760,7 +760,9 @@ implementation
             result:=cnothingnode.create;
             result:=cnothingnode.create;
             // free unused nodes
             // free unused nodes
             hloopvar.free;
             hloopvar.free;
+            hloopvar := nil;
             hloopbody.free;
             hloopbody.free;
+            hloopbody := nil;
             exit;
             exit;
           end;
           end;
         { result is a block of statements }
         { result is a block of statements }
@@ -941,7 +943,9 @@ implementation
               begin
               begin
                 result:=cerrornode.create;
                 result:=cerrornode.create;
                 hloopvar.free;
                 hloopvar.free;
+                hloopvar := nil;
                 hloopbody.free;
                 hloopbody.free;
+                hloopbody := nil;
                 MessagePos1(expr.fileinfo,parser_e_for_in_loop_cannot_be_used_for_the_type,expr.resultdef.typename);
                 MessagePos1(expr.fileinfo,parser_e_for_in_loop_cannot_be_used_for_the_type,expr.resultdef.typename);
               end
               end
             else
             else
@@ -958,7 +962,9 @@ implementation
                 if result.nodetype=errorn then
                 if result.nodetype=errorn then
                   begin
                   begin
                     hloopvar.free;
                     hloopvar.free;
+                    hloopvar := nil;
                     hloopbody.free;
                     hloopbody.free;
+                    hloopbody := nil;
                   end;
                   end;
               end
               end
             { "for x in [] do ..." always results in a never executed loop body }
             { "for x in [] do ..." always results in a never executed loop body }
@@ -997,7 +1003,9 @@ implementation
                       begin
                       begin
                         result:=cerrornode.create;
                         result:=cerrornode.create;
                         hloopvar.free;
                         hloopvar.free;
+                        hloopvar := nil;
                         hloopbody.free;
                         hloopbody.free;
+                        hloopbody := nil;
                         MessagePos1(expr.fileinfo,sym_e_no_enumerator_move,pd.returndef.typename);
                         MessagePos1(expr.fileinfo,sym_e_no_enumerator_move,pd.returndef.typename);
                       end
                       end
                     else
                     else
@@ -1007,7 +1015,9 @@ implementation
                           begin
                           begin
                             result:=cerrornode.create;
                             result:=cerrornode.create;
                             hloopvar.free;
                             hloopvar.free;
+                            hloopvar := nil;
                             hloopbody.free;
                             hloopbody.free;
+                            hloopbody := nil;
                             MessagePos1(expr.fileinfo,sym_e_no_enumerator_current,pd.returndef.typename);
                             MessagePos1(expr.fileinfo,sym_e_no_enumerator_current,pd.returndef.typename);
                           end
                           end
                         else
                         else
@@ -1038,7 +1048,9 @@ implementation
                       begin
                       begin
                         result:=cerrornode.create;
                         result:=cerrornode.create;
                         hloopvar.free;
                         hloopvar.free;
+                        hloopvar := nil;
                         hloopbody.free;
                         hloopbody.free;
+                        hloopbody := nil;
                         MessagePos1(expr.fileinfo,sym_e_no_enumerator,expr.resultdef.typename);
                         MessagePos1(expr.fileinfo,sym_e_no_enumerator,expr.resultdef.typename);
                       end;
                       end;
                     end;
                     end;
@@ -1061,6 +1073,7 @@ implementation
             n:=tfornode(n).makewhileloop;
             n:=tfornode(n).makewhileloop;
             do_firstpass(n);
             do_firstpass(n);
             hp.Free;
             hp.Free;
+            hp := nil;
           end;
           end;
       end;
       end;
 
 
@@ -1087,7 +1100,9 @@ implementation
 
 
       begin
       begin
          t1.free;
          t1.free;
+         t1 := nil;
          t2.free;
          t2.free;
+         t2 := nil;
          inherited destroy;
          inherited destroy;
       end;
       end;
 
 
@@ -1325,6 +1340,7 @@ implementation
              left:=Tunarynode(left).left;
              left:=Tunarynode(left).left;
              t.left:=nil;
              t.left:=nil;
              t.free;
              t.free;
+             t := nil;
              {Symdif operator, in case you are wondering:}
              {Symdif operator, in case you are wondering:}
              loopflags:=loopflags >< [lnf_checknegate];
              loopflags:=loopflags >< [lnf_checknegate];
            end;
            end;
@@ -1552,6 +1568,7 @@ implementation
                 if code.track_state_pass(exec_known) then
                 if code.track_state_pass(exec_known) then
                     track_state_pass:=true;
                     track_state_pass:=true;
                 code.free;
                 code.free;
+                code := nil;
             end;
             end;
         repeat
         repeat
             condition:=left.getcopy;
             condition:=left.getcopy;
@@ -1592,7 +1609,9 @@ implementation
                     done:=true;
                     done:=true;
                 end;
                 end;
             code.free;
             code.free;
+            code := nil;
             condition.free;
             condition.free;
+            condition := nil;
             firsttest:=false;
             firsttest:=false;
         until done;
         until done;
         {The loop condition is also known, for example:
         {The loop condition is also known, for example:
@@ -1615,7 +1634,7 @@ implementation
             aktstate.store_fact(condition,
             aktstate.store_fact(condition,
              cordconstnode.create(byte(checknegate),pasbool1type,true))
              cordconstnode.create(byte(checknegate),pasbool1type,true))
         else
         else
-            condition.free;
+            condition.free; // no nil needed
     end;
     end;
 {$endif}
 {$endif}
 
 
@@ -1886,6 +1905,7 @@ implementation
     destructor tfornode.destroy;
     destructor tfornode.destroy;
       begin
       begin
          loopiteration.free;
          loopiteration.free;
+         loopiteration := nil;
          inherited destroy;
          inherited destroy;
       end;
       end;
 
 
@@ -2887,6 +2907,7 @@ implementation
         { copied nodes don't need to release the symtable }
         { copied nodes don't need to release the symtable }
         if assigned(excepTSymtable) then
         if assigned(excepTSymtable) then
          excepTSymtable.free;
          excepTSymtable.free;
+         excepTSymtable := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 

+ 20 - 0
compiler/ngenutil.pas

@@ -245,6 +245,7 @@ implementation
          tlocalvarsym(tloadnode(p).symtableentry).inparentfpstruct then
          tlocalvarsym(tloadnode(p).symtableentry).inparentfpstruct then
         begin
         begin
           p.free;
           p.free;
+          p := nil;
           result:=cnothingnode.create;
           result:=cnothingnode.create;
         end
         end
       else
       else
@@ -294,6 +295,7 @@ implementation
          tlocalvarsym(tloadnode(p).symtableentry).inparentfpstruct then
          tlocalvarsym(tloadnode(p).symtableentry).inparentfpstruct then
         begin
         begin
           p.free;
           p.free;
+          p := nil;
           result:=cnothingnode.create;
           result:=cnothingnode.create;
         end
         end
       else
       else
@@ -498,6 +500,7 @@ implementation
             end;
             end;
         end;
         end;
       structlist.free;
       structlist.free;
+      structlist := nil;
     end;
     end;
 
 
 
 
@@ -866,6 +869,7 @@ implementation
                       trash_large(stat,trashn,caddnode.create(addn,cinlinenode.create(in_high_x,false,trashn.getcopy),genintconstnode(1)),trashintval)
                       trash_large(stat,trashn,caddnode.create(addn,cinlinenode.create(in_high_x,false,trashn.getcopy),genintconstnode(1)),trashintval)
                     else
                     else
                       trashn.free;
                       trashn.free;
+                      trashn := nil;
                   end;
                   end;
                 1: trash_small(stat,
                 1: trash_small(stat,
                   ctypeconvnode.create_internal(trashn,s8inttype),
                   ctypeconvnode.create_internal(trashn,s8inttype),
@@ -898,6 +902,7 @@ implementation
         end
         end
       else
       else
         trashn.free;
         trashn.free;
+        trashn := nil;
     end;
     end;
 
 
 
 
@@ -1273,6 +1278,7 @@ implementation
       );
       );
 
 
       unitinits.free;
       unitinits.free;
+      unitinits := nil;
     end;
     end;
 
 
 
 
@@ -1342,6 +1348,7 @@ implementation
       { set the count at the start }
       { set the count at the start }
       placeholder.replace(tai_const.Create_sizeint(count),sizesinttype);
       placeholder.replace(tai_const.Create_sizeint(count),sizesinttype);
       placeholder.free;
       placeholder.free;
+      placeholder := nil;
       { insert in data segment }
       { insert in data segment }
       tabledef:=tcb.end_anonymous_record;
       tabledef:=tcb.end_anonymous_record;
       sym:=current_asmdata.DefineAsmSymbol('FPC_THREADVARTABLES',AB_GLOBAL,AT_DATA,tabledef);
       sym:=current_asmdata.DefineAsmSymbol('FPC_THREADVARTABLES',AB_GLOBAL,AT_DATA,tabledef);
@@ -1351,6 +1358,7 @@ implementation
         )
         )
       );
       );
       tcb.free;
       tcb.free;
+      tcb := nil;
     end;
     end;
 
 
 
 
@@ -1406,6 +1414,7 @@ implementation
            current_module.add_public_asmsym(sym);
            current_module.add_public_asmsym(sym);
          end;
          end;
        tcb.Free;
        tcb.Free;
+       tcb := nil;
     end;
     end;
 
 
 
 
@@ -1447,6 +1456,7 @@ implementation
       { Insert TableCount at start }
       { Insert TableCount at start }
       countplaceholder.replace(Tai_const.Create_sizeint(count),sizesinttype);
       countplaceholder.replace(Tai_const.Create_sizeint(count),sizesinttype);
       countplaceholder.free;
       countplaceholder.free;
+      countplaceholder := nil;
       { insert in data segment }
       { insert in data segment }
       tabledef:=tcb.end_anonymous_record;
       tabledef:=tcb.end_anonymous_record;
       current_asmdata.asmlists[al_globals].concatlist(
       current_asmdata.asmlists[al_globals].concatlist(
@@ -1457,6 +1467,7 @@ implementation
         )
         )
       );
       );
       tcb.free;
       tcb.free;
+      tcb := nil;
     end;
     end;
 
 
 
 
@@ -1497,6 +1508,7 @@ implementation
           current_asmdata.DefineAsmSymbol(s,AB_GLOBAL,AT_DATA,rawdatadef),
           current_asmdata.DefineAsmSymbol(s,AB_GLOBAL,AT_DATA,rawdatadef),
           rawdatadef,sec_data,s,const_align(sizeof(pint))));
           rawdatadef,sec_data,s,const_align(sizeof(pint))));
       tcb.free;
       tcb.free;
+      tcb := nil;
       include(current_module.moduleflags,unitflag);
       include(current_module.moduleflags,unitflag);
     end;
     end;
 
 
@@ -1558,6 +1570,7 @@ implementation
       { Insert TableCount at start }
       { Insert TableCount at start }
       countplaceholder.replace(Tai_const.Create_sizeint(count),sizesinttype);
       countplaceholder.replace(Tai_const.Create_sizeint(count),sizesinttype);
       countplaceholder.free;
       countplaceholder.free;
+      countplaceholder := nil;
       { Add to data segment }
       { Add to data segment }
       tabledef:=tcb.end_anonymous_record;
       tabledef:=tcb.end_anonymous_record;
       current_asmdata.AsmLists[al_globals].concatList(
       current_asmdata.AsmLists[al_globals].concatList(
@@ -1567,6 +1580,7 @@ implementation
         )
         )
       );
       );
       tcb.free;
       tcb.free;
+      tcb := nil;
     end;
     end;
 
 
 
 
@@ -1597,6 +1611,7 @@ implementation
           );
           );
 
 
           tcb.free;
           tcb.free;
+          tcb := nil;
         end;
         end;
     end;
     end;
 
 
@@ -1640,6 +1655,7 @@ implementation
             tcb.get_final_asmlist(sym,ptruinttype,sec_data,'__stklen',const_align(sizeof(pint)))
             tcb.get_final_asmlist(sym,ptruinttype,sec_data,'__stklen',const_align(sizeof(pint)))
           );
           );
           tcb.free;
           tcb.free;
+          tcb := nil;
         end;
         end;
 
 
       { allocate the stack on the ZX Spectrum system }
       { allocate the stack on the ZX Spectrum system }
@@ -1672,6 +1688,7 @@ implementation
            tcb.get_final_asmlist(sym,def,sec_data,'__stack_cookie',sizeof(pint))
            tcb.get_final_asmlist(sym,def,sec_data,'__stack_cookie',sizeof(pint))
          );
          );
          tcb.free;
          tcb.free;
+         tcb := nil;
        end;
        end;
 {$ENDIF POWERPC}
 {$ENDIF POWERPC}
       { Initial heapsize }
       { Initial heapsize }
@@ -1682,6 +1699,7 @@ implementation
         tcb.get_final_asmlist(sym,ptruinttype,sec_data,'__heapsize',const_align(sizeof(pint)))
         tcb.get_final_asmlist(sym,ptruinttype,sec_data,'__heapsize',const_align(sizeof(pint)))
       );
       );
       tcb.free;
       tcb.free;
+      tcb := nil;
 
 
       { allocate an initial heap on embedded systems }
       { allocate an initial heap on embedded systems }
       if target_info.system in (systems_embedded+systems_freertos+[system_z80_zxspectrum,system_z80_msxdos]) then
       if target_info.system in (systems_embedded+systems_freertos+[system_z80_zxspectrum,system_z80_msxdos]) then
@@ -1702,6 +1720,7 @@ implementation
         tcb.get_final_asmlist(sym,u8inttype,sec_data,'__fpc_valgrind',const_align(sizeof(pint)))
         tcb.get_final_asmlist(sym,u8inttype,sec_data,'__fpc_valgrind',const_align(sizeof(pint)))
       );
       );
       tcb.free;
       tcb.free;
+      tcb := nil;
     end;
     end;
 
 
 
 
@@ -1724,6 +1743,7 @@ implementation
             )
             )
           );
           );
           tcb.free;
           tcb.free;
+          tcb := nil;
         end;
         end;
     end;
     end;
 
 

+ 22 - 0
compiler/ngtcon.pas

@@ -188,6 +188,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
              inserttypeconv(n,def);
              inserttypeconv(n,def);
            tc_emit_orddef(def,n);
            tc_emit_orddef(def,n);
            n.free;
            n.free;
+           n := nil;
         end;
         end;
 
 
       procedure ttypedconstbuilder.parse_floatdef(def:tfloatdef);
       procedure ttypedconstbuilder.parse_floatdef(def:tfloatdef);
@@ -197,6 +198,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
           n:=comp_expr([ef_accept_equal]);
           n:=comp_expr([ef_accept_equal]);
           tc_emit_floatdef(def,n);
           tc_emit_floatdef(def,n);
           n.free;
           n.free;
+          n := nil;
         end;
         end;
 
 
       procedure ttypedconstbuilder.parse_classrefdef(def:tclassrefdef);
       procedure ttypedconstbuilder.parse_classrefdef(def:tclassrefdef);
@@ -216,6 +218,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
           end;
           end;
           tc_emit_classrefdef(def,n);
           tc_emit_classrefdef(def,n);
           n.free;
           n.free;
+          n := nil;
         end;
         end;
 
 
       procedure ttypedconstbuilder.parse_pointerdef(def:tpointerdef);
       procedure ttypedconstbuilder.parse_pointerdef(def:tpointerdef);
@@ -225,6 +228,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
           p:=comp_expr([ef_accept_equal]);
           p:=comp_expr([ef_accept_equal]);
           tc_emit_pointerdef(def,p);
           tc_emit_pointerdef(def,p);
           p.free;
           p.free;
+          p := nil;
         end;
         end;
 
 
       procedure ttypedconstbuilder.parse_setdef(def:tsetdef);
       procedure ttypedconstbuilder.parse_setdef(def:tsetdef);
@@ -234,6 +238,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
           p:=comp_expr([ef_accept_equal]);
           p:=comp_expr([ef_accept_equal]);
           tc_emit_setdef(def,p);
           tc_emit_setdef(def,p);
           p.free;
           p.free;
+          p := nil;
         end;
         end;
 
 
       procedure ttypedconstbuilder.parse_enumdef(def:tenumdef);
       procedure ttypedconstbuilder.parse_enumdef(def:tenumdef);
@@ -243,6 +248,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
           p:=comp_expr([ef_accept_equal]);
           p:=comp_expr([ef_accept_equal]);
           tc_emit_enumdef(def,p);
           tc_emit_enumdef(def,p);
           p.free;
           p.free;
+          p := nil;
         end;
         end;
 
 
       procedure ttypedconstbuilder.parse_stringdef(def:tstringdef);
       procedure ttypedconstbuilder.parse_stringdef(def:tstringdef);
@@ -252,6 +258,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
           n:=comp_expr([ef_accept_equal]);
           n:=comp_expr([ef_accept_equal]);
           tc_emit_stringdef(def,n);
           tc_emit_stringdef(def,n);
           n.free;
           n.free;
+          n := nil;
         end;
         end;
 
 
     { ttypedconstbuilder }
     { ttypedconstbuilder }
@@ -479,7 +486,9 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
     destructor tasmlisttypedconstbuilder.Destroy;
     destructor tasmlisttypedconstbuilder.Destroy;
       begin
       begin
         fdatalist.free;
         fdatalist.free;
+        fdatalist := nil;
         ftcb.free;
         ftcb.free;
+        ftcb := nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;
 
 
@@ -1180,6 +1189,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
           begin
           begin
             incompatibletypes(node.resultdef,def);
             incompatibletypes(node.resultdef,def);
             node.free;
             node.free;
+            node := nil;
             consume_all_until(_SEMICOLON);
             consume_all_until(_SEMICOLON);
             result:=false;
             result:=false;
             exit;
             exit;
@@ -1191,6 +1201,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
         if (bp.curbitoffset>=AIntBits) then
         if (bp.curbitoffset>=AIntBits) then
           flush_packed_value(bp);
           flush_packed_value(bp);
         node.free;
         node.free;
+        node := nil;
       end;
       end;
 
 
     procedure tasmlisttypedconstbuilder.get_final_asmlists(out reslist, datalist: tasmlist);
     procedure tasmlisttypedconstbuilder.get_final_asmlists(out reslist, datalist: tasmlist);
@@ -1466,6 +1477,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
                end;
                end;
              ftcb.maybe_end_aggregate(def);
              ftcb.maybe_end_aggregate(def);
              n.free;
              n.free;
+             n := nil;
           end
           end
         else
         else
           begin
           begin
@@ -1505,6 +1517,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
         if codegenerror then
         if codegenerror then
           begin
           begin
             n.free;
             n.free;
+            n := nil;
             exit;
             exit;
           end;
           end;
         { let type conversion check everything needed }
         { let type conversion check everything needed }
@@ -1512,6 +1525,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
         if codegenerror then
         if codegenerror then
           begin
           begin
             n.free;
             n.free;
+            n := nil;
             exit;
             exit;
           end;
           end;
         { in case of a nested procdef initialised with a global routine }
         { in case of a nested procdef initialised with a global routine }
@@ -1605,6 +1619,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
           Message(parser_e_illegal_expression);
           Message(parser_e_illegal_expression);
         ftcb.maybe_end_aggregate(def);
         ftcb.maybe_end_aggregate(def);
         n.free;
         n.free;
+        n := nil;
       end;
       end;
 
 
 
 
@@ -1655,6 +1670,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
                   Message(parser_e_illegal_expression);
                   Message(parser_e_illegal_expression);
               end;
               end;
             n.free;
             n.free;
+            n := nil;
             exit;
             exit;
           end;
           end;
         if (def=rec_tguid) and ((token=_CSTRING) or (token=_CCHAR)) then
         if (def=rec_tguid) and ((token=_CSTRING) or (token=_CCHAR)) then
@@ -1666,6 +1682,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
             else
             else
               Message(parser_e_illegal_expression);
               Message(parser_e_illegal_expression);
             n.free;
             n.free;
+            n := nil;
             exit;
             exit;
           end;
           end;
         ftcb.maybe_begin_aggregate(def);
         ftcb.maybe_begin_aggregate(def);
@@ -1861,6 +1878,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
             else
             else
               ftcb.emit_tai(Tai_const.Create_sym(nil),def);
               ftcb.emit_tai(Tai_const.Create_sym(nil),def);
             n.free;
             n.free;
+            n := nil;
             exit;
             exit;
           end;
           end;
 
 
@@ -2062,6 +2080,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
                   Message(parser_e_illegal_expression);
                   Message(parser_e_illegal_expression);
               end;
               end;
             n.free;
             n.free;
+            n := nil;
             exit;
             exit;
           end;
           end;
         if (def=rec_tguid) and ((token=_CSTRING) or (token=_CCHAR)) then
         if (def=rec_tguid) and ((token=_CSTRING) or (token=_CCHAR)) then
@@ -2073,6 +2092,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
             else
             else
               Message(parser_e_illegal_expression);
               Message(parser_e_illegal_expression);
             n.free;
             n.free;
+            n := nil;
             exit;
             exit;
           end;
           end;
         { bitpacked record? }
         { bitpacked record? }
@@ -2186,6 +2206,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
            ) then
            ) then
           Message1(parser_w_skipped_fields_after,sorg);
           Message1(parser_w_skipped_fields_after,sorg);
         orgbasenode.free;
         orgbasenode.free;
+        orgbasenode := nil;
         basenode:=nil;
         basenode:=nil;
 
 
         consume(_RKLAMMER);
         consume(_RKLAMMER);
@@ -2225,6 +2246,7 @@ function get_next_varsym(def: tabstractrecorddef; const SymList:TFPHashObjectLis
                 basenode:=nil;
                 basenode:=nil;
               end;
               end;
             n.free;
             n.free;
+            n := nil;
             exit;
             exit;
           end;
           end;
 
 

+ 13 - 4
compiler/ninl.pas

@@ -1156,6 +1156,7 @@ implementation
                   { parameters coming after it                    }
                   { parameters coming after it                    }
                   para.right := nil;
                   para.right := nil;
                   para.free;
                   para.free;
+                  para := nil;
                 end
                 end
               else
               else
                 { read of non s/u-8/16bit, or a write }
                 { read of non s/u-8/16bit, or a write }
@@ -1197,15 +1198,18 @@ implementation
               { free the parameter, since it isn't referenced anywhere anymore }
               { free the parameter, since it isn't referenced anywhere anymore }
               para.right := nil;
               para.right := nil;
               para.free;
               para.free;
+              para := nil;
               if assigned(lenpara) then
               if assigned(lenpara) then
                 begin
                 begin
                   lenpara.right := nil;
                   lenpara.right := nil;
                   lenpara.free;
                   lenpara.free;
+                  lenpara := nil;
                 end;
                 end;
               if assigned(fracpara) then
               if assigned(fracpara) then
                 begin
                 begin
                   fracpara.right := nil;
                   fracpara.right := nil;
                   fracpara.free;
                   fracpara.free;
+                  fracpara := nil;
                 end;
                 end;
             end;
             end;
 
 
@@ -1571,17 +1575,19 @@ implementation
 
 
         { free the file parameter (it's copied inside the handle_*_read_write methods) }
         { free the file parameter (it's copied inside the handle_*_read_write methods) }
         filepara.free;
         filepara.free;
+        filepara := nil;
 
 
         { if we found an error, simply delete the generated blocknode }
         { if we found an error, simply delete the generated blocknode }
         if found_error then
         if found_error then
           begin
           begin
             { ensure that the tempinfo is freed correctly by destroying a
             { ensure that the tempinfo is freed correctly by destroying a
               delete node for it
               delete node for it
-              Note: this might happen legitimately whe parsing a generic that
-                    passes a undefined type to Write/Read }
+              Note: this might happen legitimately when parsing a generic that
+                    passes an undefined type to Write/Read }
             if assigned(filetemp) then
             if assigned(filetemp) then
-              ctempdeletenode.create(filetemp).free;
-            newblock.free
+              ctempdeletenode.create(filetemp).free; // no nil needed
+            newblock.free;
+            newblock := nil;
           end
           end
         else
         else
           begin
           begin
@@ -1832,6 +1838,7 @@ implementation
         destpara.left := nil;
         destpara.left := nil;
         destpara.right := nil;
         destpara.right := nil;
         destpara.free;
         destpara.free;
+        destpara := nil;
 
 
         { check if we used a temp for code and whether we have to store }
         { check if we used a temp for code and whether we have to store }
         { it to the real code parameter                                 }
         { it to the real code parameter                                 }
@@ -5395,6 +5402,7 @@ implementation
 
 
             ppn.left:=nil;
             ppn.left:=nil;
             paras.free;
             paras.free;
+            paras := nil;
           end
           end
         else
         else
           result:=ccallnode.createintern('fpc_shortstr_copy',paras);
           result:=ccallnode.createintern('fpc_shortstr_copy',paras);
@@ -5954,6 +5962,7 @@ implementation
            end;
            end;
 
 
          list.free;
          list.free;
+         list := nil;
        end;
        end;
 
 
 
 

+ 1 - 0
compiler/nmat.pas

@@ -671,6 +671,7 @@ implementation
                     addstatement(statements,ctempdeletenode.create_normal_temp(resulttemp));
                     addstatement(statements,ctempdeletenode.create_normal_temp(resulttemp));
                     addstatement(statements,ctemprefnode.create(resulttemp));
                     addstatement(statements,ctemprefnode.create(resulttemp));
                     right.Free;
                     right.Free;
+                    right := nil;
                   end
                   end
                 else
                 else
                   begin
                   begin

+ 2 - 0
compiler/nobj.pas

@@ -977,6 +977,7 @@ implementation
                       prot_get_procdefs_recursive(ImplIntf,ImplIntf.IntfDef);
                       prot_get_procdefs_recursive(ImplIntf,ImplIntf.IntfDef);
                     end;
                     end;
                   handledprotocols.free;
                   handledprotocols.free;
+                  handledprotocols := nil;
                 end
                 end
               else
               else
                 internalerror(2009091801);
                 internalerror(2009091801);
@@ -992,6 +993,7 @@ implementation
         vmtbuilder:=TVMTBuilder.create(def);
         vmtbuilder:=TVMTBuilder.create(def);
         vmtbuilder.build;
         vmtbuilder.build;
         vmtbuilder.free;
         vmtbuilder.free;
+        vmtbuilder := nil;
       end;
       end;
 
 
 end.
 end.

+ 3 - 0
compiler/node.pas

@@ -1094,6 +1094,7 @@ implementation
     destructor tunarynode.destroy;
     destructor tunarynode.destroy;
       begin
       begin
         left.free;
         left.free;
+        left := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -1201,6 +1202,7 @@ implementation
     destructor tbinarynode.destroy;
     destructor tbinarynode.destroy;
       begin
       begin
         right.free;
         right.free;
+        right := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -1355,6 +1357,7 @@ implementation
     destructor ttertiarynode.destroy;
     destructor ttertiarynode.destroy;
       begin
       begin
         third.free;
         third.free;
+        third := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 

+ 9 - 6
compiler/nset.pas

@@ -26,7 +26,7 @@ unit nset;
 interface
 interface
 
 
     uses
     uses
-       cclasses,constexp,
+       sysutils,cclasses,constexp,
        node,globtype,globals,
        node,globtype,globals,
        aasmbase,ncon,nflw,symtype;
        aasmbase,ncon,nflw,symtype;
 
 
@@ -539,8 +539,8 @@ implementation
            deletecaselabels(p^.less);
            deletecaselabels(p^.less);
          if (p^.label_type = ltConstString) then
          if (p^.label_type = ltConstString) then
            begin
            begin
-             p^._low_str.Free;
-             p^._high_str.Free;
+             FreeAndNil(p^._low_str);
+             FreeAndNil(p^._high_str);
            end;
            end;
          dispose(p);
          dispose(p);
       end;
       end;
@@ -645,14 +645,16 @@ implementation
         hp : pcaseblock;
         hp : pcaseblock;
       begin
       begin
          elseblock.free;
          elseblock.free;
+         elseblock := nil;
          deletecaselabels(flabels);
          deletecaselabels(flabels);
          for i:=0 to blocks.count-1 do
          for i:=0 to blocks.count-1 do
            begin
            begin
-             pcaseblock(blocks[i])^.statement.free;
+             FreeAndNil(pcaseblock(blocks[i])^.statement);
              hp:=pcaseblock(blocks[i]);
              hp:=pcaseblock(blocks[i]);
              dispose(hp);
              dispose(hp);
            end;
            end;
          blocks.free;
          blocks.free;
+         blocks := nil;
          inherited destroy;
          inherited destroy;
       end;
       end;
 
 
@@ -811,6 +813,7 @@ implementation
             end;
             end;
           { will free its elements too because of create(true) }
           { will free its elements too because of create(true) }
           blocklist.free;
           blocklist.free;
+          blocklist := nil;
           typecheckpass(result);
           typecheckpass(result);
         end;
         end;
 
 
@@ -1416,8 +1419,8 @@ implementation
               result := insertlabel(p^.greater)
               result := insertlabel(p^.greater)
           else
           else
             begin
             begin
-              hcaselabel^._low_str.free;
-              hcaselabel^._high_str.free;
+              FreeAndNil(hcaselabel^._low_str);
+              FreeAndNil(hcaselabel^._high_str);
               dispose(hcaselabel);
               dispose(hcaselabel);
               Message(parser_e_double_caselabel);
               Message(parser_e_double_caselabel);
               result:=nil;
               result:=nil;

+ 1 - 0
compiler/objcdef.pas

@@ -140,6 +140,7 @@ implementation
         for i:=0 to variantstarts.count-1 do
         for i:=0 to variantstarts.count-1 do
           encodedstr:=encodedstr+'})';
           encodedstr:=encodedstr+'})';
         variantstarts.free;
         variantstarts.free;
+        variantstarts := nil;
         encodedstr:=encodedstr+'}';
         encodedstr:=encodedstr+'}';
         result:=true
         result:=true
       end;
       end;

+ 31 - 0
compiler/objcgutl.pas

@@ -173,6 +173,7 @@ procedure objcreatestringpoolentryintern(p: pchar; len: longint; pooltype: tcons
           tcb.get_final_asmlist(strlab,def,stringsec,strlab.name,1)
           tcb.get_final_asmlist(strlab,def,stringsec,strlab.name,1)
         );
         );
         tcb.free;
         tcb.free;
+        tcb := nil;
         def:=cpointerdef.getreusable(def);
         def:=cpointerdef.getreusable(def);
       end
       end
     else
     else
@@ -207,6 +208,7 @@ procedure objcfinishstringrefpoolentry(entry: phashsetitem; stringpool: tconstpo
           tcb.get_final_asmlist(reflab,strdef,refsec,reflab.name,sizeof(pint))
           tcb.get_final_asmlist(reflab,strdef,refsec,reflab.name,sizeof(pint))
           );
           );
         tcb.free;
         tcb.free;
+        tcb := nil;
 
 
         { in case of a class reference, also add a lazy symbol reference for
         { in case of a class reference, also add a lazy symbol reference for
           the class (the linker requires this for the fragile ABI). }
           the class (the linker requires this for the fragile ABI). }
@@ -252,6 +254,7 @@ procedure objcfinishclassrefnfpoolentry(entry: phashsetitem; classdef: tobjectde
           tcb.get_final_asmlist(reflab,voidpointertype,sec_objc_cls_refs,reflab.name,sizeof(pint))
           tcb.get_final_asmlist(reflab,voidpointertype,sec_objc_cls_refs,reflab.name,sizeof(pint))
         );
         );
         tcb.free;
         tcb.free;
+        tcb := nil;
       end;
       end;
   end;
   end;
 
 
@@ -371,6 +374,7 @@ procedure tobjcrttiwriter.gen_objc_methods(list: tasmlist; objccls: tobjectdef;
       )
       )
     );
     );
     tcb.free;
     tcb.free;
+    tcb := nil;
   end;
   end;
 
 
 
 
@@ -420,9 +424,13 @@ procedure tobjcrttiwriter.gen_objc_protocol_elements(list: tasmlist; protocol: t
       optclssym:=nil;
       optclssym:=nil;
 
 
     reqinstmlist.Free;
     reqinstmlist.Free;
+    reqinstmlist := nil;
     reqclsmlist.Free;
     reqclsmlist.Free;
+    reqclsmlist := nil;
     optinstmlist.Free;
     optinstmlist.Free;
+    optinstmlist := nil;
     optclsmlist.Free;
     optclsmlist.Free;
+    optclsmlist := nil;
 end;
 end;
 
 
 
 
@@ -498,6 +506,7 @@ procedure tobjcrttiwriter.gen_objc_protocol_list(list: tasmlist; protolist: tfpo
       )
       )
     );
     );
     tcb.free;
     tcb.free;
+    tcb := nil;
     { the symbol will point to a record }
     { the symbol will point to a record }
   end;
   end;
 
 
@@ -547,6 +556,7 @@ begin
       listsym,tcb.end_anonymous_record,section,sectname,sizeof(pint))
       listsym,tcb.end_anonymous_record,section,sectname,sizeof(pint))
   );
   );
   tcb.free;
   tcb.free;
+  tcb := nil;
 end;
 end;
 
 
 
 
@@ -609,11 +619,17 @@ constructor tobjcrttiwriter.create(_abi: tobjcabi);
 destructor tobjcrttiwriter.destroy;
 destructor tobjcrttiwriter.destroy;
   begin
   begin
     classdefs.free;
     classdefs.free;
+    classdefs := nil;
     classsyms.free;
     classsyms.free;
+    classsyms := nil;
     classrttidefs.free;
     classrttidefs.free;
+    classrttidefs := nil;
     catrttidefs.free;
     catrttidefs.free;
+    catrttidefs := nil;
     catdefs.free;
     catdefs.free;
+    catdefs := nil;
     catsyms.free;
     catsyms.free;
+    catsyms := nil;
     inherited destroy;
     inherited destroy;
   end;
   end;
 
 
@@ -721,6 +737,7 @@ function tobjcrttiwriter_fragile.gen_objc_protocol_ext(list: TAsmList; optinstsy
           )
           )
         );
         );
         tcb.free;
         tcb.free;
+        tcb := nil;
       end
       end
     else
     else
       Result:=nil;
       Result:=nil;
@@ -773,6 +790,7 @@ procedure tobjcrttiwriter_fragile.gen_objc_protocol(list:TAsmList; protocol: tob
       )
       )
     );
     );
     tcb.free;
     tcb.free;
+    tcb := nil;
   end;
   end;
 
 
 
 
@@ -844,6 +862,7 @@ procedure tobjcrttiwriter_fragile.gen_objc_category_sections(list:TAsmList; objc
       )
       )
     );
     );
     tcb.free;
     tcb.free;
+    tcb := nil;
 
 
     catlabel:=catsym;
     catlabel:=catsym;
     catlabeldef:=catdef;
     catlabeldef:=catdef;
@@ -1036,6 +1055,7 @@ procedure tobjcrttiwriter_fragile.gen_objc_classes_sections(list:TAsmList; objcl
       )
       )
     );
     );
     tcb.free;
     tcb.free;
+    tcb := nil;
 
 
     classlabel:=clssym;
     classlabel:=clssym;
     classlabeldef:=clsDef;
     classlabeldef:=clsDef;
@@ -1135,6 +1155,7 @@ procedure tobjcrttiwriter_fragile.gen_objc_info_sections(list: tasmlist);
           end;
           end;
       end;
       end;
     superclasses.free;
     superclasses.free;
+    superclasses := nil;
     { reference symbols for all classes and categories defined in this unit }
     { reference symbols for all classes and categories defined in this unit }
     for i:=0 to classdefs.count-1 do
     for i:=0 to classdefs.count-1 do
       list.concat(tai_symbol.Createname_global_value('.objc_class_name_'+tobjectdef(classdefs[i]).objextname^,AT_DATA,0,0,voidpointertype));
       list.concat(tai_symbol.Createname_global_value('.objc_class_name_'+tobjectdef(classdefs[i]).objextname^,AT_DATA,0,0,voidpointertype));
@@ -1240,6 +1261,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_ivars(list: tasmlist; objccls: tob
                 )
                 )
               );
               );
               tcb.free;
               tcb.free;
+              tcb := nil;
               inc(vcnt);
               inc(vcnt);
             end
             end
           else
           else
@@ -1289,6 +1311,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_ivars(list: tasmlist; objccls: tob
       )
       )
     );
     );
     tcb.free;
     tcb.free;
+    tcb := nil;
   end;
   end;
 
 
 
 
@@ -1395,6 +1418,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_protocol(list: tasmlist; protocol:
       )
       )
     );
     );
     tcb.free;
     tcb.free;
+    tcb := nil;
   end;
   end;
 
 
 (*
 (*
@@ -1455,6 +1479,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_category_sections(list:TAsmList; o
       )
       )
     );
     );
     tcb.free;
     tcb.free;
+    tcb := nil;
 
 
     catlabel:=catsym;
     catlabel:=catsym;
     catlabeldef:=catdef;
     catlabeldef:=catdef;
@@ -1667,6 +1692,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_class_ro_part(list: tasmlist; objc
       )
       )
     );
     );
     tcb.free;
     tcb.free;
+    tcb := nil;
     classrolabel:=rosym;
     classrolabel:=rosym;
   end;
   end;
 
 
@@ -1781,6 +1807,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_classes_sections(list:TAsmList; ob
       )
       )
     );
     );
     metatcb.free;
     metatcb.free;
+    metatcb := nil;
 
 
     { 2) regular class declaration }
     { 2) regular class declaration }
     { the isa }
     { the isa }
@@ -1801,6 +1828,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_classes_sections(list:TAsmList; ob
       )
       )
     );
     );
     isatcb.free;
     isatcb.free;
+    isatcb := nil;
 
 
     classlabel:=clssym;
     classlabel:=clssym;
     classlabeldef:=classdef;
     classlabeldef:=classdef;
@@ -1888,7 +1916,9 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_info_sections(list: tasmlist);
     addclasslist(list,sec_objc_nlcatlist,target_asm.labelprefix+'_OBJC_LABEL_NONLAZY_CATEGORY_$',nonlazycategories);
     addclasslist(list,sec_objc_nlcatlist,target_asm.labelprefix+'_OBJC_LABEL_NONLAZY_CATEGORY_$',nonlazycategories);
 
 
     nonlazyclasses.free;
     nonlazyclasses.free;
+    nonlazyclasses := nil;
     nonlazycategories.free;
     nonlazycategories.free;
+    nonlazycategories := nil;
     { the non-fragile abi doesn't have any module info, nor lazy references
     { the non-fragile abi doesn't have any module info, nor lazy references
       to used classes or to parent classes }
       to used classes or to parent classes }
   end;
   end;
@@ -1920,6 +1950,7 @@ procedure MaybeGenerateObjectiveCImageInfo(globalst, localst: tsymtable);
         objcrttiwriter.gen_objc_rtti_sections(current_asmdata.asmlists[al_objc_data],localst);
         objcrttiwriter.gen_objc_rtti_sections(current_asmdata.asmlists[al_objc_data],localst);
         objcrttiwriter.gen_objc_info_sections(current_asmdata.asmlists[al_objc_data]);
         objcrttiwriter.gen_objc_info_sections(current_asmdata.asmlists[al_objc_data]);
         objcrttiwriter.free;
         objcrttiwriter.free;
+        objcrttiwriter := nil;
       end;
       end;
   end;
   end;
 
 

+ 40 - 9
compiler/ogbase.pas

@@ -1075,10 +1075,15 @@ implementation
     destructor TObjSection.destroy;
     destructor TObjSection.destroy;
       begin
       begin
         if assigned(Data) then
         if assigned(Data) then
-          Data.Free;
+          begin
+            FData.Free;
+            FData := nil;
+          end;
         stringdispose(FCachedFullName);
         stringdispose(FCachedFullName);
         ObjRelocations.Free;
         ObjRelocations.Free;
+        ObjRelocations := nil;
         VTRefList.Free;
         VTRefList.Free;
+        VTRefList := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -1432,17 +1437,21 @@ implementation
 {$endif}
 {$endif}
         ResetCachedAsmSymbols;
         ResetCachedAsmSymbols;
         FCachedAsmSymbolList.free;
         FCachedAsmSymbolList.free;
+        FCachedAsmSymbolList := nil;
         FObjSymbolList.free;
         FObjSymbolList.free;
+        FObjSymbolList := nil;
 {$ifdef MEMDEBUG}
 {$ifdef MEMDEBUG}
         MemObjSymbols.Stop;
         MemObjSymbols.Stop;
 {$endif}
 {$endif}
-        GroupsList.free;
+        FGroupsList.free;
+        FGroupsList := nil;
 
 
         { Sections }
         { Sections }
 {$ifdef MEMDEBUG}
 {$ifdef MEMDEBUG}
         MemObjSections.Start;
         MemObjSections.Start;
 {$endif}
 {$endif}
         FObjSectionList.free;
         FObjSectionList.free;
+        FObjSectionList := nil;
 {$ifdef MEMDEBUG}
 {$ifdef MEMDEBUG}
         MemObjSections.Stop;
         MemObjSections.Stop;
 {$endif}
 {$endif}
@@ -2125,6 +2134,7 @@ implementation
     destructor TExeVTable.Destroy;
     destructor TExeVTable.Destroy;
       begin
       begin
         ChildList.Free;
         ChildList.Free;
+        ChildList := nil;
         if assigned(EntryArray) then
         if assigned(EntryArray) then
           Freemem(EntryArray);
           Freemem(EntryArray);
       end;
       end;
@@ -2220,7 +2230,8 @@ implementation
 
 
     destructor TExeSection.destroy;
     destructor TExeSection.destroy;
       begin
       begin
-        ObjSectionList.Free;
+        FObjSectionList.Free;
+        FObjSectionList := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -2285,6 +2296,7 @@ implementation
     destructor TStaticLibrary.destroy;
     destructor TStaticLibrary.destroy;
       begin
       begin
         FPayload.Free;
         FPayload.Free;
+        FPayload := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -2325,7 +2337,8 @@ implementation
 
 
     destructor TImportLibrary.destroy;
     destructor TImportLibrary.destroy;
       begin
       begin
-        ImportSymbolList.Free;
+        FImportSymbolList.Free;
+        FImportSymbolList := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -2394,16 +2407,27 @@ implementation
     destructor TExeOutput.destroy;
     destructor TExeOutput.destroy;
       begin
       begin
         FExeSymbolList.free;
         FExeSymbolList.free;
-        UnresolvedExeSymbols.free;
-        ExternalObjSymbols.free;
+        FExeSymbolList := nil;
+        FUnresolvedExeSymbols.free;
+        FUnresolvedExeSymbols := nil;
+        FExternalObjSymbols.free;
+        FExternalObjSymbols := nil;
         FProvidedObjSymbols.free;
         FProvidedObjSymbols.free;
+        FProvidedObjSymbols := nil;
         FIndirectObjSymbols.free;
         FIndirectObjSymbols.free;
-        CommonObjSymbols.free;
-        ExeVTableList.free;
+        FIndirectObjSymbols := nil;
+        FCommonObjSymbols.free;
+        FCommonObjSymbols := nil;
+        FExeVTableList.free;
+        FExeVTableList := nil;
         FExeSectionList.free;
         FExeSectionList.free;
+        FExeSectionList := nil;
         ComdatGroups.free;
         ComdatGroups.free;
-        ObjDatalist.free;
+        ComdatGroups := nil;
+        FObjDatalist.free;
+        FObjDatalist := nil;
         FWriter.free;
         FWriter.free;
+        FWriter := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -2590,6 +2614,7 @@ implementation
             CurrExeSec.AddObjSection(objsec);
             CurrExeSec.AddObjSection(objsec);
           end;
           end;
         TmpObjSectionList.Free;
         TmpObjSectionList.Free;
+        TmpObjSectionList := nil;
       end;
       end;
 
 
 
 
@@ -3185,6 +3210,7 @@ implementation
                               objinput:=lib.ObjInputClass.Create;
                               objinput:=lib.ObjInputClass.Create;
                               objinput.ReadObjData(lib.ArReader,objdata);
                               objinput.ReadObjData(lib.ArReader,objdata);
                               objinput.free;
                               objinput.free;
+                              objinput := nil;
                               AddObjData(objdata);
                               AddObjData(objdata);
                               LoadObjDataSymbols(objdata);
                               LoadObjDataSymbols(objdata);
                               lib.ArReader.CloseFile;
                               lib.ArReader.CloseFile;
@@ -3313,7 +3339,9 @@ implementation
         if cs_link_opt_vtable in current_settings.globalswitches then
         if cs_link_opt_vtable in current_settings.globalswitches then
           BuildVTableTree(VTInheritList,VTEntryList);
           BuildVTableTree(VTInheritList,VTEntryList);
         VTInheritList.Free;
         VTInheritList.Free;
+        VTInheritList := nil;
         VTEntryList.Free;
         VTEntryList.Free;
+        VTEntryList := nil;
       end;
       end;
 
 
 
 
@@ -3446,6 +3474,7 @@ implementation
               end;
               end;
           end;
           end;
         list.Free;
         list.Free;
+        list := nil;
       end;
       end;
 
 
 
 
@@ -4149,6 +4178,8 @@ initialization
 
 
 finalization
 finalization
   memobjsymbols.free;
   memobjsymbols.free;
+  memobjsymbols := nil;
   memobjsections.free;
   memobjsections.free;
+  memobjsections := nil;
 {$endif MEMDEBUG}
 {$endif MEMDEBUG}
 end.
 end.

+ 5 - 0
compiler/ogcoff.pas

@@ -1797,7 +1797,9 @@ const pemagic : array[0..3] of byte = (
     destructor TCoffObjOutput.destroy;
     destructor TCoffObjOutput.destroy;
       begin
       begin
         FCoffSyms.free;
         FCoffSyms.free;
+        FCoffSyms := nil;
         FCoffStrs.free;
         FCoffStrs.free;
+        FCoffStrs := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -2271,6 +2273,7 @@ const pemagic : array[0..3] of byte = (
     destructor TCoffObjInput.destroy;
     destructor TCoffObjInput.destroy;
       begin
       begin
         FCoffSyms.free;
         FCoffSyms.free;
+        FCoffSyms := nil;
         FCoffStrs:=nil;
         FCoffStrs:=nil;
         FSymTbl:=nil;
         FSymTbl:=nil;
         FSecTbl:=nil;
         FSecTbl:=nil;
@@ -3404,6 +3407,7 @@ const pemagic : array[0..3] of byte = (
           end;
           end;
         { Release }
         { Release }
         FCoffStrs.Free;
         FCoffStrs.Free;
+        FCoffStrs := nil;
         result:=true;
         result:=true;
       end;
       end;
 
 
@@ -3951,6 +3955,7 @@ const pemagic : array[0..3] of byte = (
             readdllproc(DLLName,FuncName);
             readdllproc(DLLName,FuncName);
           end;
           end;
         DLLReader.Free;
         DLLReader.Free;
+        DLLReader := nil;
       end;
       end;
 
 
 {$ifdef arm}
 {$ifdef arm}

+ 9 - 0
compiler/ogelf.pas

@@ -741,6 +741,7 @@ implementation
     destructor TElfDynamicObjData.destroy;
     destructor TElfDynamicObjData.destroy;
       begin
       begin
         FVersionDefs.free;
         FVersionDefs.free;
+        FVersionDefs := nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;
 
 
@@ -1832,10 +1833,15 @@ implementation
     destructor TElfExeOutput.Destroy;
     destructor TElfExeOutput.Destroy;
       begin
       begin
         dyncopysyms.Free;
         dyncopysyms.Free;
+        dyncopysyms := nil;
         neededlist.Free;
         neededlist.Free;
+        neededlist := nil;
         segmentlist.Free;
         segmentlist.Free;
+        segmentlist := nil;
         dynsymlist.Free;
         dynsymlist.Free;
+        dynsymlist := nil;
         dynreloclist.Free;
         dynreloclist.Free;
+        dynreloclist := nil;
         if assigned(dynsymnames) then
         if assigned(dynsymnames) then
           FreeMem(dynsymnames);
           FreeMem(dynsymnames);
         stringdispose(FInterpreter);
         stringdispose(FInterpreter);
@@ -2334,7 +2340,9 @@ implementation
         if (newsections.count<>0) then
         if (newsections.count<>0) then
           ReplaceExeSectionList(allsections);
           ReplaceExeSectionList(allsections);
         newsections.Free;
         newsections.Free;
+        newsections := nil;
         allsections.Free;
         allsections.Free;
+        allsections := nil;
       end;
       end;
 
 
 
 
@@ -3292,6 +3300,7 @@ implementation
     destructor TElfSegment.Destroy;
     destructor TElfSegment.Destroy;
       begin
       begin
         FSectionList.Free;
         FSectionList.Free;
+        FSectionList := nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;
 
 

+ 7 - 1
compiler/ogmacho.pas

@@ -1141,13 +1141,19 @@ uses
       TrailZeros;
       TrailZeros;
 
 
       if not Assigned(strsec) then
       if not Assigned(strsec) then
-        symstr.Free;
+        begin
+          symstr.Free;
+          symstr := nil;
+        end;
 
 
       TrailZeros;
       TrailZeros;
 
 
       mfile.Free;
       mfile.Free;
+      mfile := nil;
       symList.Free;
       symList.Free;
+      symList := nil;
       IndirIndex.Free;
       IndirIndex.Free;
+      IndirIndex := nil;
     end;
     end;
 
 
 
 

+ 4 - 0
compiler/ognlm.pas

@@ -398,9 +398,13 @@ end;
     destructor TNLMexeoutput.destroy;
     destructor TNLMexeoutput.destroy;
       begin
       begin
         nlmImports.Free;
         nlmImports.Free;
+        nlmImports := nil;
         nlmImpNames.Free;
         nlmImpNames.Free;
+        nlmImpNames := nil;
         nlmSymbols.Free;
         nlmSymbols.Free;
+        nlmSymbols := nil;
         FexportFunctionOffsets.Free;
         FexportFunctionOffsets.Free;
+        FexportFunctionOffsets := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 

+ 83 - 1
compiler/ogomf.pas

@@ -882,6 +882,7 @@ implementation
     destructor TOmfRelocation.Destroy;
     destructor TOmfRelocation.Destroy;
       begin
       begin
         FOmfFixup.Free;
         FOmfFixup.Free;
+        FOmfFixup := nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;
 
 
@@ -1029,6 +1030,7 @@ implementation
     destructor TOmfObjSection.destroy;
     destructor TOmfObjSection.destroy;
       begin
       begin
         FLinNumEntries.Free;
         FLinNumEntries.Free;
+        FLinNumEntries := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -1076,7 +1078,9 @@ implementation
     destructor TOmfObjData.destroy;
     destructor TOmfObjData.destroy;
       begin
       begin
         FExportedSymbolList.Free;
         FExportedSymbolList.Free;
+        FExportedSymbolList := nil;
         FImportLibraryList.Free;
         FImportLibraryList.Free;
+        FImportLibraryList := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -1419,6 +1423,7 @@ implementation
               ChunkFixupStart:=ChunkFixupEnd+1;
               ChunkFixupStart:=ChunkFixupEnd+1;
             end;
             end;
             RawRecord.Free;
             RawRecord.Free;
+            RawRecord := nil;
           end;
           end;
       end;
       end;
 
 
@@ -1448,7 +1453,9 @@ implementation
               end;
               end;
 
 
             LinNumRec.Free;
             LinNumRec.Free;
+            LinNumRec := nil;
             RawRecord.Free;
             RawRecord.Free;
+            RawRecord := nil;
           end;
           end;
       end;
       end;
 
 
@@ -1512,11 +1519,13 @@ implementation
                   RawRecord.WriteTo(FWriter);
                   RawRecord.WriteTo(FWriter);
                 end;
                 end;
               PubDefRec.Free;
               PubDefRec.Free;
+              PubDefRec := nil;
             end;
             end;
 
 
         for i:=0 to Data.ObjSectionList.Count-1 do
         for i:=0 to Data.ObjSectionList.Count-1 do
           FreeAndNil(PubNamesForSection[i]);
           FreeAndNil(PubNamesForSection[i]);
         RawRecord.Free;
         RawRecord.Free;
+        RawRecord := nil;
       end;
       end;
 
 
     procedure TOmfObjOutput.WriteEXTDEFs(Data: TObjData);
     procedure TOmfObjOutput.WriteEXTDEFs(Data: TObjData);
@@ -1552,10 +1561,13 @@ implementation
                 RawRecord.WriteTo(FWriter);
                 RawRecord.WriteTo(FWriter);
               end;
               end;
             ExtDefRec.Free;
             ExtDefRec.Free;
+            ExtDefRec := nil;
           end;
           end;
 
 
         ExtNames.Free;
         ExtNames.Free;
+        ExtNames := nil;
         RawRecord.Free;
         RawRecord.Free;
+        RawRecord := nil;
       end;
       end;
 
 
     function TOmfObjOutput.writeData(Data:TObjData):boolean;
     function TOmfObjOutput.writeData(Data:TObjData):boolean;
@@ -1595,6 +1607,7 @@ implementation
         Header.EncodeTo(RawRecord);
         Header.EncodeTo(RawRecord);
         RawRecord.WriteTo(FWriter);
         RawRecord.WriteTo(FWriter);
         Header.Free;
         Header.Free;
+        Header := nil;
 
 
         { write translator COMENT header }
         { write translator COMENT header }
         Translator_COMENT:=TOmfRecord_COMENT.Create;
         Translator_COMENT:=TOmfRecord_COMENT.Create;
@@ -1604,6 +1617,7 @@ implementation
         Translator_COMENT.EncodeTo(RawRecord);
         Translator_COMENT.EncodeTo(RawRecord);
         RawRecord.WriteTo(FWriter);
         RawRecord.WriteTo(FWriter);
         Translator_COMENT.Free;
         Translator_COMENT.Free;
+        Translator_COMENT := nil;
 
 
         if (target_dbg.id=dbg_codeview) or
         if (target_dbg.id=dbg_codeview) or
            ((ds_dwarf_omf_linnum in current_settings.debugswitches) and
            ((ds_dwarf_omf_linnum in current_settings.debugswitches) and
@@ -1615,6 +1629,7 @@ implementation
             DebugFormat_COMENT.EncodeTo(RawRecord);
             DebugFormat_COMENT.EncodeTo(RawRecord);
             RawRecord.WriteTo(FWriter);
             RawRecord.WriteTo(FWriter);
             DebugFormat_COMENT.Free;
             DebugFormat_COMENT.Free;
+            DebugFormat_COMENT := nil;
           end;
           end;
 
 
         LNames.Clear;
         LNames.Clear;
@@ -1639,6 +1654,7 @@ implementation
             RawRecord.WriteTo(FWriter);
             RawRecord.WriteTo(FWriter);
           end;
           end;
         LNamesRec.Free;
         LNamesRec.Free;
+        LNamesRec := nil;
 
 
         { write SEGDEF record(s) }
         { write SEGDEF record(s) }
         for I:=1 to Segments.Count-1 do
         for I:=1 to Segments.Count-1 do
@@ -1670,6 +1686,7 @@ implementation
         LinkPassSeparator_COMENT.EncodeTo(RawRecord);
         LinkPassSeparator_COMENT.EncodeTo(RawRecord);
         RawRecord.WriteTo(FWriter);
         RawRecord.WriteTo(FWriter);
         LinkPassSeparator_COMENT.Free;
         LinkPassSeparator_COMENT.Free;
+        LinkPassSeparator_COMENT := nil;
 
 
         { write section content, interleaved with fixups }
         { write section content, interleaved with fixups }
         WriteSections(Data);
         WriteSections(Data);
@@ -1679,8 +1696,10 @@ implementation
         ModEnd.EncodeTo(RawRecord);
         ModEnd.EncodeTo(RawRecord);
         RawRecord.WriteTo(FWriter);
         RawRecord.WriteTo(FWriter);
         ModEnd.Free;
         ModEnd.Free;
+        ModEnd := nil;
 
 
         RawRecord.Free;
         RawRecord.Free;
+        RawRecord := nil;
         result:=true;
         result:=true;
       end;
       end;
 
 
@@ -1698,8 +1717,11 @@ implementation
     destructor TOmfObjOutput.Destroy;
     destructor TOmfObjOutput.Destroy;
       begin
       begin
         FGroups.Free;
         FGroups.Free;
+        FGroups := nil;
         FSegments.Free;
         FSegments.Free;
+        FSegments := nil;
         FLNames.Free;
         FLNames.Free;
+        FLNames := nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;
 
 
@@ -1718,6 +1740,7 @@ implementation
         Header.EncodeTo(RawRecord);
         Header.EncodeTo(RawRecord);
         RawRecord.WriteTo(FWriter);
         RawRecord.WriteTo(FWriter);
         Header.Free;
         Header.Free;
+        Header := nil;
 
 
         { write IMPDEF record }
         { write IMPDEF record }
         DllImport_COMENT_IMPDEF:=TOmfRecord_COMENT_IMPDEF.Create;
         DllImport_COMENT_IMPDEF:=TOmfRecord_COMENT_IMPDEF.Create;
@@ -1746,8 +1769,10 @@ implementation
         ModEnd.EncodeTo(RawRecord);
         ModEnd.EncodeTo(RawRecord);
         RawRecord.WriteTo(FWriter);
         RawRecord.WriteTo(FWriter);
         ModEnd.Free;
         ModEnd.Free;
+        ModEnd := nil;
 
 
         RawRecord.Free;
         RawRecord.Free;
+        RawRecord := nil;
       end;
       end;
 
 
 {****************************************************************************
 {****************************************************************************
@@ -1777,6 +1802,7 @@ implementation
         LNamesRec.Names:=LNames;
         LNamesRec.Names:=LNames;
         LNamesRec.DecodeFrom(RawRec);
         LNamesRec.DecodeFrom(RawRec);
         LNamesRec.Free;
         LNamesRec.Free;
+        LNamesRec := nil;
         Result:=True;
         Result:=True;
       end;
       end;
 
 
@@ -1795,6 +1821,7 @@ implementation
           begin
           begin
             InputError('Segment name index out of range');
             InputError('Segment name index out of range');
             SegDefRec.Free;
             SegDefRec.Free;
+            SegDefRec := nil;
             exit;
             exit;
           end;
           end;
         SegmentName:=LNames[SegDefRec.SegmentNameIndex];
         SegmentName:=LNames[SegDefRec.SegmentNameIndex];
@@ -1802,6 +1829,7 @@ implementation
           begin
           begin
             InputError('Segment class name index out of range');
             InputError('Segment class name index out of range');
             SegDefRec.Free;
             SegDefRec.Free;
+            SegDefRec := nil;
             exit;
             exit;
           end;
           end;
         SegClassName:=LNames[SegDefRec.ClassNameIndex];
         SegClassName:=LNames[SegDefRec.ClassNameIndex];
@@ -1809,6 +1837,7 @@ implementation
           begin
           begin
             InputError('Segment overlay name index out of range');
             InputError('Segment overlay name index out of range');
             SegDefRec.Free;
             SegDefRec.Free;
+            SegDefRec := nil;
             exit;
             exit;
           end;
           end;
         OverlayName:=LNames[SegDefRec.OverlayNameIndex];
         OverlayName:=LNames[SegDefRec.OverlayNameIndex];
@@ -1830,12 +1859,14 @@ implementation
             begin
             begin
               InputError('Absolute segment alignment not supported');
               InputError('Absolute segment alignment not supported');
               SegDefRec.Free;
               SegDefRec.Free;
+              SegDefRec := nil;
               exit;
               exit;
             end;
             end;
           saNotDefined:
           saNotDefined:
             begin
             begin
               InputError('Invalid (unsupported/undefined) OMF segment alignment');
               InputError('Invalid (unsupported/undefined) OMF segment alignment');
               SegDefRec.Free;
               SegDefRec.Free;
+              SegDefRec := nil;
               exit;
               exit;
             end;
             end;
         end;
         end;
@@ -1861,6 +1892,7 @@ implementation
           begin
           begin
             InputError('Segment too large');
             InputError('Segment too large');
             SegDefRec.Free;
             SegDefRec.Free;
+            SegDefRec := nil;
             exit;
             exit;
           end;
           end;
         objsec.Size:=SegDefRec.SegmentLength;
         objsec.Size:=SegDefRec.SegmentLength;
@@ -1872,6 +1904,7 @@ implementation
            (SegmentName='FPC') then
            (SegmentName='FPC') then
           objsec.SecOptions:=objsec.SecOptions+[oso_keep];
           objsec.SecOptions:=objsec.SecOptions+[oso_keep];
         SegDefRec.Free;
         SegDefRec.Free;
+        SegDefRec := nil;
         Result:=True;
         Result:=True;
       end;
       end;
 
 
@@ -1889,6 +1922,7 @@ implementation
           begin
           begin
             InputError('Group name index out of range');
             InputError('Group name index out of range');
             GrpDefRec.Free;
             GrpDefRec.Free;
+            GrpDefRec := nil;
             exit;
             exit;
           end;
           end;
         GroupName:=LNames[GrpDefRec.GroupNameIndex];
         GroupName:=LNames[GrpDefRec.GroupNameIndex];
@@ -1903,11 +1937,13 @@ implementation
               begin
               begin
                 InputError('Segment name index out of range in group definition');
                 InputError('Segment name index out of range in group definition');
                 GrpDefRec.Free;
                 GrpDefRec.Free;
+                GrpDefRec := nil;
                 exit;
                 exit;
               end;
               end;
             SecGroup.members[i]:=TOmfObjSection(objdata.ObjSectionList[SegIndex-1]);
             SecGroup.members[i]:=TOmfObjSection(objdata.ObjSectionList[SegIndex-1]);
           end;
           end;
         GrpDefRec.Free;
         GrpDefRec.Free;
+        GrpDefRec := nil;
         Result:=True;
         Result:=True;
       end;
       end;
 
 
@@ -1939,6 +1975,7 @@ implementation
             objsym.size:=0;
             objsym.size:=0;
           end;
           end;
         ExtDefRec.Free;
         ExtDefRec.Free;
+        ExtDefRec := nil;
         Result:=True;
         Result:=True;
       end;
       end;
 
 
@@ -1962,6 +1999,7 @@ implementation
           begin
           begin
             InputError('Public symbol''s group name index out of range');
             InputError('Public symbol''s group name index out of range');
             PubDefRec.Free;
             PubDefRec.Free;
+            PubDefRec := nil;
             exit;
             exit;
           end;
           end;
         if PubDefRec.BaseGroupIndex<>0 then
         if PubDefRec.BaseGroupIndex<>0 then
@@ -1972,12 +2010,14 @@ implementation
           begin
           begin
             InputError('Public symbol''s segment name index out of range');
             InputError('Public symbol''s segment name index out of range');
             PubDefRec.Free;
             PubDefRec.Free;
+            PubDefRec := nil;
             exit;
             exit;
           end;
           end;
         if PubDefRec.BaseSegmentIndex=0 then
         if PubDefRec.BaseSegmentIndex=0 then
           begin
           begin
             InputError('Public symbol uses absolute addressing, which is not supported by this linker');
             InputError('Public symbol uses absolute addressing, which is not supported by this linker');
             PubDefRec.Free;
             PubDefRec.Free;
+            PubDefRec := nil;
             exit;
             exit;
           end;
           end;
         objsec:=TOmfObjSection(objdata.ObjSectionList[PubDefRec.BaseSegmentIndex-1]);
         objsec:=TOmfObjSection(objdata.ObjSectionList[PubDefRec.BaseSegmentIndex-1]);
@@ -2001,6 +2041,7 @@ implementation
               objsec.FFirstSym:=objsym;
               objsec.FFirstSym:=objsym;
           end;
           end;
         PubDefRec.Free;
         PubDefRec.Free;
+        PubDefRec := nil;
         Result:=True;
         Result:=True;
       end;
       end;
 
 
@@ -2020,18 +2061,21 @@ implementation
               begin
               begin
                 InputError('Physical start address not supported');
                 InputError('Physical start address not supported');
                 ModEndRec.Free;
                 ModEndRec.Free;
+                ModEndRec := nil;
                 exit;
                 exit;
               end;
               end;
             if not (ModEndRec.TargetMethod in [ftmSegmentIndex,ftmSegmentIndexNoDisp]) then
             if not (ModEndRec.TargetMethod in [ftmSegmentIndex,ftmSegmentIndexNoDisp]) then
               begin
               begin
                 InputError('Target method for start address other than "Segment Index" is not supported');
                 InputError('Target method for start address other than "Segment Index" is not supported');
                 ModEndRec.Free;
                 ModEndRec.Free;
+                ModEndRec := nil;
                 exit;
                 exit;
               end;
               end;
             if (ModEndRec.TargetDatum<1) or (ModEndRec.TargetDatum>objdata.ObjSectionList.Count) then
             if (ModEndRec.TargetDatum<1) or (ModEndRec.TargetDatum>objdata.ObjSectionList.Count) then
               begin
               begin
                 InputError('Segment name index for start address out of range');
                 InputError('Segment name index for start address out of range');
                 ModEndRec.Free;
                 ModEndRec.Free;
+                ModEndRec := nil;
                 exit;
                 exit;
               end;
               end;
             case ModEndRec.FrameMethod of
             case ModEndRec.FrameMethod of
@@ -2041,12 +2085,14 @@ implementation
                     begin
                     begin
                       InputError('Frame segment name index for start address out of range');
                       InputError('Frame segment name index for start address out of range');
                       ModEndRec.Free;
                       ModEndRec.Free;
+                      ModEndRec := nil;
                       exit;
                       exit;
                     end;
                     end;
                   if ModEndRec.FrameDatum<>ModEndRec.TargetDatum then
                   if ModEndRec.FrameDatum<>ModEndRec.TargetDatum then
                     begin
                     begin
                       InputError('Frame segment different than target segment is not supported supported for start address');
                       InputError('Frame segment different than target segment is not supported supported for start address');
                       ModEndRec.Free;
                       ModEndRec.Free;
+                      ModEndRec := nil;
                       exit;
                       exit;
                     end;
                     end;
                   basegroup:=nil;
                   basegroup:=nil;
@@ -2057,6 +2103,7 @@ implementation
                     begin
                     begin
                       InputError('Frame group name index for start address out of range');
                       InputError('Frame group name index for start address out of range');
                       ModEndRec.Free;
                       ModEndRec.Free;
+                      ModEndRec := nil;
                       exit;
                       exit;
                     end;
                     end;
                   basegroup:=TObjSectionGroup(objdata.GroupsList[ModEndRec.FrameDatum-1]);
                   basegroup:=TObjSectionGroup(objdata.GroupsList[ModEndRec.FrameDatum-1]);
@@ -2065,6 +2112,7 @@ implementation
                 begin
                 begin
                   InputError('Frame method for start address other than "Segment Index" or "Group Index" is not supported');
                   InputError('Frame method for start address other than "Segment Index" or "Group Index" is not supported');
                   ModEndRec.Free;
                   ModEndRec.Free;
+                  ModEndRec := nil;
                   exit;
                   exit;
                 end;
                 end;
             end;
             end;
@@ -2079,6 +2127,7 @@ implementation
             objsym.size:=0;
             objsym.size:=0;
           end;
           end;
         ModEndRec.Free;
         ModEndRec.Free;
+        ModEndRec := nil;
         Result:=True;
         Result:=True;
       end;
       end;
 
 
@@ -2176,6 +2225,7 @@ implementation
                   begin
                   begin
                     InputError('Invalid checksum in OMF record');
                     InputError('Invalid checksum in OMF record');
                     FixupRawRec.Free;
                     FixupRawRec.Free;
+                    FixupRawRec := nil;
                     exit;
                     exit;
                   end;
                   end;
               end;
               end;
@@ -2193,9 +2243,14 @@ implementation
                       begin
                       begin
                         InputError('FIXUP subrecord without previous LEDATA or LIDATA record');
                         InputError('FIXUP subrecord without previous LEDATA or LIDATA record');
                         Fixup.Free;
                         Fixup.Free;
+                        Fixup := nil;
                         Thread.Free;
                         Thread.Free;
+                        Thread := nil;
                         if FixupRawRec<>RawRec then
                         if FixupRawRec<>RawRec then
-                          FixupRawRec.Free;
+                          begin
+                            FixupRawRec.Free;
+                            FixupRawRec := nil;
+                          end;
                         exit;
                         exit;
                       end;
                       end;
                     NextOfs:=Fixup.ReadAt(FixupRawRec,NextOfs);
                     NextOfs:=Fixup.ReadAt(FixupRawRec,NextOfs);
@@ -2210,7 +2265,9 @@ implementation
                   end;
                   end;
               end;
               end;
             Fixup.Free;
             Fixup.Free;
+            Fixup := nil;
             Thread.Free;
             Thread.Free;
+            Thread := nil;
             if FixupRawRec<>RawRec then
             if FixupRawRec<>RawRec then
               FixupRawRec.Free;
               FixupRawRec.Free;
             { always set it to null, so that we read the next record on the next }
             { always set it to null, so that we read the next record on the next }
@@ -2237,6 +2294,7 @@ implementation
           TOmfObjData(objdata).AddImportSymbol(MaybeAddDllExt(ImpDefRec.ModuleName),ImpDefRec.Name,SymName,0,false);
           TOmfObjData(objdata).AddImportSymbol(MaybeAddDllExt(ImpDefRec.ModuleName),ImpDefRec.Name,SymName,0,false);
         Result:=True;
         Result:=True;
         ImpDefRec.Free;
         ImpDefRec.Free;
+        ImpDefRec := nil;
       end;
       end;
 
 
     function TOmfObjInput.ReadExpDef(Rec: TOmfRecord_COMENT; objdata: TObjData): Boolean;
     function TOmfObjInput.ReadExpDef(Rec: TOmfRecord_COMENT; objdata: TObjData): Boolean;
@@ -2259,6 +2317,7 @@ implementation
           ExpDefRec.ExportOrdinal);
           ExpDefRec.ExportOrdinal);
         Result:=True;
         Result:=True;
         ExpDefRec.Free;
         ExpDefRec.Free;
+        ExpDefRec := nil;
       end;
       end;
 
 
     function TOmfObjInput.ImportOmfFixup(objdata: TObjData; objsec: TOmfObjSection; Fixup: TOmfSubRecord_FIXUP): Boolean;
     function TOmfObjInput.ImportOmfFixup(objdata: TObjData; objsec: TOmfObjSection; Fixup: TOmfSubRecord_FIXUP): Boolean;
@@ -2571,11 +2630,17 @@ implementation
     destructor TOmfObjInput.destroy;
     destructor TOmfObjInput.destroy;
       begin
       begin
         FCOMENTRecord.Free;
         FCOMENTRecord.Free;
+        FCOMENTRecord := nil;
         FRawRecord.Free;
         FRawRecord.Free;
+        FRawRecord := nil;
         FFixupThreads.Free;
         FFixupThreads.Free;
+        FFixupThreads := nil;
         FPubDefs.Free;
         FPubDefs.Free;
+        FPubDefs := nil;
         FExtDefs.Free;
         FExtDefs.Free;
+        FExtDefs := nil;
         FLNames.Free;
         FLNames.Free;
+        FLNames := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -2832,6 +2897,7 @@ implementation
     destructor TMZExeUnifiedLogicalSegment.destroy;
     destructor TMZExeUnifiedLogicalSegment.destroy;
       begin
       begin
         FObjSectionList.Free;
         FObjSectionList.Free;
+        FObjSectionList := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -2885,6 +2951,7 @@ implementation
     destructor TMZExeUnifiedLogicalGroup.destroy;
     destructor TMZExeUnifiedLogicalGroup.destroy;
       begin
       begin
         FSegmentList.Free;
         FSegmentList.Free;
+        FSegmentList := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -3434,6 +3501,7 @@ implementation
         Result:=True;
         Result:=True;
 cleanup:
 cleanup:
         shstrtabsect_data.Free;
         shstrtabsect_data.Free;
+        shstrtabsect_data := nil;
       end;
       end;
 
 
     procedure TMZExeOutput.Load_Symbol(const aname: string);
     procedure TMZExeOutput.Load_Symbol(const aname: string);
@@ -3772,9 +3840,13 @@ cleanup:
     destructor TMZExeOutput.destroy;
     destructor TMZExeOutput.destroy;
       begin
       begin
         FHeader.Free;
         FHeader.Free;
+        FHeader := nil;
         FDwarfUnifiedLogicalSegments.Free;
         FDwarfUnifiedLogicalSegments.Free;
+        FDwarfUnifiedLogicalSegments := nil;
         FExeUnifiedLogicalGroups.Free;
         FExeUnifiedLogicalGroups.Free;
+        FExeUnifiedLogicalGroups := nil;
         FExeUnifiedLogicalSegments.Free;
         FExeUnifiedLogicalSegments.Free;
+        FExeUnifiedLogicalSegments := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -4270,6 +4342,7 @@ cleanup:
     destructor TNewExeRelocationList.Destroy;
     destructor TNewExeRelocationList.Destroy;
       begin
       begin
         FInternalList.Free;
         FInternalList.Free;
+        FInternalList := nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;
 
 
@@ -4322,6 +4395,7 @@ cleanup:
     destructor TNewExeSection.destroy;
     destructor TNewExeSection.destroy;
       begin
       begin
         FRelocations.Free;
         FRelocations.Free;
+        FRelocations := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -4707,12 +4781,19 @@ cleanup:
     destructor TNewExeOutput.destroy;
     destructor TNewExeOutput.destroy;
       begin
       begin
         FEntryTable.Free;
         FEntryTable.Free;
+        FEntryTable := nil;
         FImportedNameTable.Free;
         FImportedNameTable.Free;
+        FImportedNameTable := nil;
         FModuleReferenceTable.Free;
         FModuleReferenceTable.Free;
+        FModuleReferenceTable := nil;
         FNonresidentNameTable.Free;
         FNonresidentNameTable.Free;
+        FNonresidentNameTable := nil;
         FResidentNameTable.Free;
         FResidentNameTable.Free;
+        FResidentNameTable := nil;
         FResourceTable.Free;
         FResourceTable.Free;
+        FResourceTable := nil;
         FHeader.Free;
         FHeader.Free;
+        FHeader := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -4771,6 +4852,7 @@ cleanup:
             CurrExeSec.AddObjSection(objsec);
             CurrExeSec.AddObjSection(objsec);
           end;
           end;
         TmpObjSectionList.Free;
         TmpObjSectionList.Free;
+        TmpObjSectionList := nil;
       end;
       end;
 
 
     procedure TNewExeOutput.MemPos_Start;
     procedure TNewExeOutput.MemPos_Start;

+ 1 - 0
compiler/ogrel.pas

@@ -1230,6 +1230,7 @@ implementation
                 end;
                 end;
             end;
             end;
         instance.Free;
         instance.Free;
+        instance := nil;
       end;
       end;
 
 
 
 

+ 25 - 7
compiler/ogwasm.pas

@@ -27,7 +27,7 @@ interface
 
 
     uses
     uses
       { common }
       { common }
-      cclasses,globtype,
+      sysutils,cclasses,globtype,
       { target }
       { target }
       systems,cpubase,
       systems,cpubase,
       { assembler }
       { assembler }
@@ -699,6 +699,7 @@ implementation
     destructor TWasmObjSymbolLinkingData.Destroy;
     destructor TWasmObjSymbolLinkingData.Destroy;
       begin
       begin
         FuncType.Free;
         FuncType.Free;
+        FuncType := nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;
 
 
@@ -735,6 +736,7 @@ implementation
     destructor TWasmObjRelocation.Destroy;
     destructor TWasmObjRelocation.Destroy;
       begin
       begin
         FuncType.Free;
         FuncType.Free;
+        FuncType := nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;
 
 
@@ -771,6 +773,7 @@ implementation
     destructor TWasmObjSymbol.Destroy;
     destructor TWasmObjSymbol.Destroy;
       begin
       begin
         LinkingData.Free;
         LinkingData.Free;
+        LinkingData := nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;
 
 
@@ -794,6 +797,7 @@ implementation
     destructor TWasmObjSymbolExtraData.Destroy;
     destructor TWasmObjSymbolExtraData.Destroy;
       begin
       begin
         EncodedLocals.Free;
         EncodedLocals.Free;
+        EncodedLocals := nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;
 
 
@@ -1076,7 +1080,9 @@ implementation
         i: Integer;
         i: Integer;
       begin
       begin
         FObjSymbolsExtraDataList.Free;
         FObjSymbolsExtraDataList.Free;
+        FObjSymbolsExtraDataList := nil;
         FFuncTypes.Free;
         FFuncTypes.Free;
+        FFuncTypes := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -1277,6 +1283,7 @@ implementation
         ft:=TWasmFuncType.Create([],tt.params);
         ft:=TWasmFuncType.Create([],tt.params);
         i:=FFuncTypes.AddOrGetFuncType(ft);
         i:=FFuncTypes.AddOrGetFuncType(ft);
         ft.free;
         ft.free;
+        ft := nil;
         ObjSymExtraData.ExceptionTagTypeIdx:=i;
         ObjSymExtraData.ExceptionTagTypeIdx:=i;
       end;
       end;
 
 
@@ -2460,21 +2467,31 @@ implementation
         k: TWasmLinkingSubsectionType;
         k: TWasmLinkingSubsectionType;
       begin
       begin
         for i in TWasmSectionID do
         for i in TWasmSectionID do
-          FWasmSections[i].Free;
+          FreeAndNil(FWasmSections[i]);
         for j in TWasmCustomSectionType do
         for j in TWasmCustomSectionType do
-          FWasmCustomSections[j].Free;
+          FreeAndNil(FWasmCustomSections[j]);
         for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
         for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
-          FWasmLinkingSubsections[k].Free;
+          FreeAndNil(FWasmLinkingSubsections[k]);
         FWasmSymbolTable.Free;
         FWasmSymbolTable.Free;
+        FWasmSymbolTable := nil;
         FWasmRelocationCodeTable.Free;
         FWasmRelocationCodeTable.Free;
+        FWasmRelocationCodeTable := nil;
         FWasmRelocationDataTable.Free;
         FWasmRelocationDataTable.Free;
+        FWasmRelocationDataTable := nil;
         FWasmRelocationDebugFrameTable.Free;
         FWasmRelocationDebugFrameTable.Free;
+        FWasmRelocationDebugFrameTable := nil;
         FWasmRelocationDebugInfoTable.Free;
         FWasmRelocationDebugInfoTable.Free;
+        FWasmRelocationDebugInfoTable := nil;
         FWasmRelocationDebugLineTable.Free;
         FWasmRelocationDebugLineTable.Free;
+        FWasmRelocationDebugLineTable := nil;
         FWasmRelocationDebugAbbrevTable.Free;
         FWasmRelocationDebugAbbrevTable.Free;
+        FWasmRelocationDebugAbbrevTable := nil;
         FWasmRelocationDebugArangesTable.Free;
         FWasmRelocationDebugArangesTable.Free;
+        FWasmRelocationDebugArangesTable := nil;
         FWasmRelocationDebugRangesTable.Free;
         FWasmRelocationDebugRangesTable.Free;
+        FWasmRelocationDebugRangesTable := nil;
         FWasmRelocationDebugStrTable.Free;
         FWasmRelocationDebugStrTable.Free;
+        FWasmRelocationDebugStrTable := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -5571,12 +5588,13 @@ implementation
         k: TWasmNameSubsectionType;
         k: TWasmNameSubsectionType;
       begin
       begin
         for i in TWasmSectionID do
         for i in TWasmSectionID do
-          FWasmSections[i].Free;
+          FreeAndNil(FWasmSections[i]);
         for j in TWasmCustomSectionType do
         for j in TWasmCustomSectionType do
-          FWasmCustomSections[j].Free;
+          FreeAndNil(FWasmCustomSections[j]);
         for k:=low(FWasmNameSubsections) to high(FWasmNameSubsections) do
         for k:=low(FWasmNameSubsections) to high(FWasmNameSubsections) do
-          FWasmNameSubsections[k].Free;
+          FreeAndNil(FWasmNameSubsections[k]);
         FFuncTypes.Free;
         FFuncTypes.Free;
+        FFuncTypes := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 

+ 4 - 2
compiler/omfbase.pas

@@ -27,6 +27,7 @@ unit omfbase;
 interface
 interface
 {$H+}
 {$H+}
   uses
   uses
+    sysutils,
     cclasses,
     cclasses,
     aasmbase,
     aasmbase,
     owbase;
     owbase;
@@ -2396,6 +2397,7 @@ implementation
   destructor TOmfSubRecord_LINNUM_MsLink_LineNumberList.Destroy;
   destructor TOmfSubRecord_LINNUM_MsLink_LineNumberList.Destroy;
     begin
     begin
       FLineNumbers.Free;
       FLineNumbers.Free;
+      FLineNumbers := nil;
       inherited Destroy;
       inherited Destroy;
     end;
     end;
 
 
@@ -2515,8 +2517,8 @@ implementation
     begin
     begin
       for t in TOmfFixupThread do
       for t in TOmfFixupThread do
         begin
         begin
-          FTargetThreads[t].Free;
-          FFrameThreads[t].Free;
+          FreeAndNil(FTargetThreads[t]);
+          FreeAndNil(FFrameThreads[t]);
         end;
         end;
       inherited Destroy;
       inherited Destroy;
     end;
     end;

+ 1 - 0
compiler/optconstprop.pas

@@ -240,6 +240,7 @@ unit optconstprop;
                     n:=tinlinenode(n).getaddsub_for_incdec;
                     n:=tinlinenode(n).getaddsub_for_incdec;
                     Include(n.flags, nf_internal);
                     Include(n.flags, nf_internal);
                     oldnode.free;
                     oldnode.free;
+                    oldnode := nil;
                     tree_modified:=true;
                     tree_modified:=true;
                     { do not continue, value changed, if further const. propagations are possible, this is done
                     { do not continue, value changed, if further const. propagations are possible, this is done
                       by the next pass }
                       by the next pass }

+ 7 - 6
compiler/optcse.pas

@@ -29,7 +29,7 @@ unit optcse;
   interface
   interface
 
 
     uses
     uses
-      node;
+      sysutils,node;
 
 
     {
     {
       the function  creates non optimal code so far:
       the function  creates non optimal code so far:
@@ -523,16 +523,17 @@ unit optcse;
                 { clean up unused trees }
                 { clean up unused trees }
                 for i:=0 to lists.nodelist.count-1 do
                 for i:=0 to lists.nodelist.count-1 do
                   if lists.equalto[i]<>pointer(-1) then
                   if lists.equalto[i]<>pointer(-1) then
-                    tnode(lists.nodelist[i]).free;
+                    tnode(lists.nodelist[i]).free; // no nil needed
 {$ifdef csedebug}
 {$ifdef csedebug}
                 writeln('nodes: ',lists.nodelist.count);
                 writeln('nodes: ',lists.nodelist.count);
                 writeln('==========================================');
                 writeln('==========================================');
 {$endif csedebug}
 {$endif csedebug}
-                lists.nodelist.free;
-                lists.locationlist.free;
-                lists.equalto.free;
-                lists.refs.free;
+                FreeAndNil(lists.nodelist);
+                FreeAndNil(lists.locationlist);
+                FreeAndNil(lists.equalto);
+                FreeAndNil(lists.refs);
                 templist.free;
                 templist.free;
+                templist := nil;
 
 
                 if assigned(statements) then
                 if assigned(statements) then
                   begin
                   begin

+ 2 - 0
compiler/optdfa.pas

@@ -672,7 +672,9 @@ unit optdfa;
     destructor TDFABuilder.Destroy;
     destructor TDFABuilder.Destroy;
       begin
       begin
         Resultnode.free;
         Resultnode.free;
+        Resultnode := nil;
         nodemap.free;
         nodemap.free;
+        nodemap := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 

+ 11 - 0
compiler/options.pas

@@ -2355,14 +2355,23 @@ end;
 destructor TOption.Destroy;
 destructor TOption.Destroy;
 begin
 begin
   ParaIncludeCfgPath.Free;
   ParaIncludeCfgPath.Free;
+  ParaIncludeCfgPath := nil;
   ParaIncludePath.Free;
   ParaIncludePath.Free;
+  ParaIncludePath := nil;
   ParaObjectPath.Free;
   ParaObjectPath.Free;
+  ParaObjectPath := nil;
   ParaUnitPath.Free;
   ParaUnitPath.Free;
+  ParaUnitPath := nil;
   ParaLibraryPath.Free;
   ParaLibraryPath.Free;
+  ParaLibraryPath := nil;
   ParaFrameworkPath.Free;
   ParaFrameworkPath.Free;
+  ParaFrameworkPath := nil;
   parapackagepath.Free;
   parapackagepath.Free;
+  parapackagepath := nil;
   ParaPackages.Free;
   ParaPackages.Free;
+  ParaPackages := nil;
   paranamespaces.free;
   paranamespaces.free;
+  paranamespaces := nil;
 end;
 end;
 
 
 procedure TOption.Interpret_A_l(opt, more: TCmdStr);
 procedure TOption.Interpret_A_l(opt, more: TCmdStr);
@@ -5156,6 +5165,7 @@ begin
       cmditem:=TCmdStrListItem(cmditem.Next);
       cmditem:=TCmdStrListItem(cmditem.Next);
     end;
     end;
   tmplist.Free;
   tmplist.Free;
+  tmplist := nil;
 
 
   { add unit environment and exepath to the unit search path }
   { add unit environment and exepath to the unit search path }
   if inputfilepath<>'' then
   if inputfilepath<>'' then
@@ -6014,4 +6024,5 @@ initialization
 finalization
 finalization
   if assigned(option) then
   if assigned(option) then
    option.free;
    option.free;
+   option := nil;
 end.
 end.

+ 1 - 0
compiler/optloop.pas

@@ -606,6 +606,7 @@ unit optloop;
 
 
             n:=internalstatements(newcodestatements);
             n:=internalstatements(newcodestatements);
             oldn.Free;
             oldn.Free;
+            oldn := nil;
             addstatement(newcodestatements,initcode);
             addstatement(newcodestatements,initcode);
             addstatement(newcodestatements,newfor);
             addstatement(newcodestatements,newfor);
             addstatement(newcodestatements,deletecode);
             addstatement(newcodestatements,deletecode);

+ 2 - 0
compiler/opttail.pas

@@ -217,6 +217,7 @@ unit opttail;
                       end;
                       end;
 
 
                     oldnodetree.free;
                     oldnodetree.free;
+                    oldnodetree := nil;
 
 
                     do_firstpass(n);
                     do_firstpass(n);
                     result:=true;
                     result:=true;
@@ -298,6 +299,7 @@ unit opttail;
           end
           end
         else
         else
           labelnode.free;
           labelnode.free;
+          labelnode := nil;
       end;
       end;
 
 
 end.
 end.

+ 8 - 0
compiler/optvirt.pas

@@ -192,7 +192,9 @@ unit optvirt;
       begin
       begin
         { fchilds owns its members, so it will free them too }
         { fchilds owns its members, so it will free them too }
         fchilds.free;
         fchilds.free;
+        fchilds:=nil;
         fcalledvmtmethods.free;
         fcalledvmtmethods.free;
+        fcalledvmtmethods:=nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -270,7 +272,9 @@ unit optvirt;
     destructor tinheritancetree.destroy;
     destructor tinheritancetree.destroy;
       begin
       begin
         froots.free;
         froots.free;
+        froots:=nil;
         classrefdefs.free;
         classrefdefs.free;
+        classrefdefs:=nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
       
       
@@ -635,6 +639,7 @@ unit optvirt;
           if assigned(fstaticmethodnames[i]) then
           if assigned(fstaticmethodnames[i]) then
             freemem(fstaticmethodnames[i]);
             freemem(fstaticmethodnames[i]);
         fstaticmethodnames.free;
         fstaticmethodnames.free;
+        fstaticmethodnames:=nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -668,6 +673,7 @@ unit optvirt;
     destructor tunitdevirtinfo.destroy;
     destructor tunitdevirtinfo.destroy;
       begin
       begin
         fclasses.free;
         fclasses.free;
+        fclasses:=nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -739,6 +745,7 @@ unit optvirt;
     destructor tprogdevirtinfo.destroy;
     destructor tprogdevirtinfo.destroy;
       begin
       begin
         funits.free;
         funits.free;
+        funits:=nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -879,6 +886,7 @@ unit optvirt;
 {$endif DEBUG_DEVIRT}
 {$endif DEBUG_DEVIRT}
          inheritancetree.foreachnode(@converttreenode,nil);
          inheritancetree.foreachnode(@converttreenode,nil);
          inheritancetree.free;
          inheritancetree.free;
+         inheritancetree:=nil;
       end;
       end;
 
 
 
 

+ 6 - 0
compiler/owar.pas

@@ -182,9 +182,13 @@ implementation
         if Errorcount=0 then
         if Errorcount=0 then
          writear;
          writear;
         arData.Free;
         arData.Free;
+        arData := nil;
         symreloc.Free;
         symreloc.Free;
+        symreloc := nil;
         symstr.Free;
         symstr.Free;
+        symstr := nil;
         lfnstr.Free;
         lfnstr.Free;
+        lfnstr := nil;
       end;
       end;
 
 
 
 
@@ -320,6 +324,7 @@ implementation
          end;
          end;
         ardata.WriteStream(arf);
         ardata.WriteStream(arf);
         Arf.Free;
         Arf.Free;
+        Arf := nil;
       end;
       end;
 
 
 
 
@@ -354,6 +359,7 @@ implementation
       begin
       begin
         inherited closefile;
         inherited closefile;
         ArSymbols.Free;
         ArSymbols.Free;
+        ArSymbols := nil;
         LFNStrs:=nil;
         LFNStrs:=nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;

+ 2 - 0
compiler/owbase.pas

@@ -151,6 +151,7 @@ begin
    writebuf;
    writebuf;
   fn:=f.filename;
   fn:=f.filename;
   f.free;
   f.free;
+  f := nil;
 { Remove if size is 0 }
 { Remove if size is 0 }
   if size=0 then
   if size=0 then
    DeleteFile(fn);
    DeleteFile(fn);
@@ -282,6 +283,7 @@ begin
   setlength(buf,bufmax);
   setlength(buf,bufmax);
   f.read(buf[0],bufmax);
   f.read(buf[0],bufmax);
   f.free;
   f.free;
+  f := nil;
   bufidx:=0;
   bufidx:=0;
   opened:=true;
   opened:=true;
   openfile:=true;
   openfile:=true;

+ 17 - 0
compiler/owomflib.pas

@@ -166,6 +166,7 @@ implementation
     destructor TOmfLibObjectWriter.TOmfLibObjectModule.Destroy;
     destructor TOmfLibObjectWriter.TOmfLibObjectModule.Destroy;
       begin
       begin
         FObjData.Free;
         FObjData.Free;
+        FObjData := nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;
 
 
@@ -205,8 +206,11 @@ implementation
         if Errorcount=0 then
         if Errorcount=0 then
           WriteLib;
           WriteLib;
         FLibData.Free;
         FLibData.Free;
+        FLibData := nil;
         FObjectModules.Free;
         FObjectModules.Free;
+        FObjectModules := nil;
         FDictionary.Free;
         FDictionary.Free;
+        FDictionary := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 
@@ -231,6 +235,7 @@ implementation
         if RawRec.RecordType<>RT_THEADR then
         if RawRec.RecordType<>RT_THEADR then
           begin
           begin
             RawRec.Free;
             RawRec.Free;
+            RawRec := nil;
             InternalError(2018060801);
             InternalError(2018060801);
           end;
           end;
         ObjHeader:=TOmfRecord_THEADR.Create;
         ObjHeader:=TOmfRecord_THEADR.Create;
@@ -238,7 +243,9 @@ implementation
         { create a dictionary entry with the module name }
         { create a dictionary entry with the module name }
         TOmfLibDictionaryEntry.Create(FDictionary,ModName2DictEntry(ObjHeader.ModuleName),FCurrentModuleIndex);
         TOmfLibDictionaryEntry.Create(FDictionary,ModName2DictEntry(ObjHeader.ModuleName),FCurrentModuleIndex);
         ObjHeader.Free;
         ObjHeader.Free;
+        ObjHeader := nil;
         RawRec.Free;
         RawRec.Free;
+        RawRec := nil;
         fobjsize:=0;
         fobjsize:=0;
       end;
       end;
 
 
@@ -274,7 +281,9 @@ implementation
         FLibData.seek(0);
         FLibData.seek(0);
         RawRec.WriteTo(FLibData);
         RawRec.WriteTo(FLibData);
         Header.Free;
         Header.Free;
+        Header := nil;
         RawRec.Free;
         RawRec.Free;
+        RawRec := nil;
       end;
       end;
 
 
     procedure TOmfLibObjectWriter.WriteFooter;
     procedure TOmfLibObjectWriter.WriteFooter;
@@ -289,7 +298,9 @@ implementation
         Footer.EncodeTo(RawRec);
         Footer.EncodeTo(RawRec);
         RawRec.WriteTo(FLibData);
         RawRec.WriteTo(FLibData);
         Footer.Free;
         Footer.Free;
+        Footer := nil;
         RawRec.Free;
         RawRec.Free;
+        RawRec := nil;
       end;
       end;
 
 
     function TOmfLibObjectWriter.TryPageSize(aPageSize: Integer): Boolean;
     function TOmfLibObjectWriter.TryPageSize(aPageSize: Integer): Boolean;
@@ -365,6 +376,7 @@ implementation
         WriteHeader(DictStart,DictBlocks);
         WriteHeader(DictStart,DictBlocks);
         FLibData.WriteStream(libf);
         FLibData.WriteStream(libf);
         libf.Free;
         libf.Free;
+        libf := nil;
       end;
       end;
 
 
     function TOmfLibObjectWriter.WriteDictionary: Word;
     function TOmfLibObjectWriter.WriteDictionary: Word;
@@ -484,7 +496,9 @@ implementation
       FIsCaseSensitive:=Header.CaseSensitive;
       FIsCaseSensitive:=Header.CaseSensitive;
       ReadDictionary(Header.DictionaryOffset, Header.DictionarySizeInBlocks);
       ReadDictionary(Header.DictionaryOffset, Header.DictionarySizeInBlocks);
       Header.Free;
       Header.Free;
+      Header := nil;
       RawRecord.Free;
       RawRecord.Free;
+      RawRecord := nil;
     end;
     end;
 
 
   procedure TOmfLibObjectReader.ReadDictionary(DictionaryOffset: DWord; DictionarySizeInBlocks: Word);
   procedure TOmfLibObjectReader.ReadDictionary(DictionaryOffset: DWord; DictionarySizeInBlocks: Word);
@@ -571,6 +585,7 @@ implementation
     begin
     begin
       inherited closefile;
       inherited closefile;
       LibSymbols.Free;
       LibSymbols.Free;
+      LibSymbols := nil;
       inherited Destroy;
       inherited Destroy;
     end;
     end;
 
 
@@ -594,7 +609,9 @@ implementation
       Header.DecodeFrom(RawRec);
       Header.DecodeFrom(RawRec);
       CurrMemberName:=Header.ModuleName;
       CurrMemberName:=Header.ModuleName;
       Header.Free;
       Header.Free;
+      Header := nil;
       RawRec.Free;
       RawRec.Free;
+      RawRec := nil;
 
 
       { go back to the beginning of the file }
       { go back to the beginning of the file }
       inherited Seek(CurrMemberPos);
       inherited Seek(CurrMemberPos);

+ 1 - 0
compiler/paramgr.pas

@@ -868,4 +868,5 @@ initialization
   ;
   ;
 finalization
 finalization
   paramanager.free;
   paramanager.free;
+  paramanager := nil;
 end.
 end.

+ 8 - 2
compiler/parser.pas

@@ -101,6 +101,7 @@ implementation
               begin
               begin
                 loaded_units.remove(hp);
                 loaded_units.remove(hp);
                 hp.free;
                 hp.free;
+                hp := nil;
               end;
               end;
             hp:=hp2;
             hp:=hp2;
           end;
           end;
@@ -294,22 +295,25 @@ implementation
            still assinged }
            still assinged }
          if assigned(current_scanner) then
          if assigned(current_scanner) then
           begin
           begin
-            current_scanner.free;
+            current_scanner.free; // no nil needed
             set_current_scanner(nil);
             set_current_scanner(nil);
-
           end;
           end;
 
 
          { close scanner }
          { close scanner }
          DoneScanner;
          DoneScanner;
 
 
          RTTIWriter.free;
          RTTIWriter.free;
+         RTTIWriter := nil;
 
 
          { close ppas,deffile }
          { close ppas,deffile }
          asmres.free;
          asmres.free;
+         asmres := nil;
          deffile.free;
          deffile.free;
+         deffile := nil;
 
 
          { free list of .o files }
          { free list of .o files }
          SmartLinkOFiles.Free;
          SmartLinkOFiles.Free;
+         SmartLinkOFiles := nil;
       end;
       end;
 
 
 
 
@@ -388,9 +392,11 @@ implementation
          until false;
          until false;
        { free scanner }
        { free scanner }
          current_scanner.free;
          current_scanner.free;
+         current_scanner := nil;
          set_current_scanner(nil);
          set_current_scanner(nil);
        { close }
        { close }
          preprocfile.free;
          preprocfile.free;
+         preprocfile := nil;
       end;
       end;
 {$endif PREPROCWRITE}
 {$endif PREPROCWRITE}
 
 

+ 1 - 0
compiler/pass_1.pas

@@ -246,6 +246,7 @@ implementation
         aktstate:=Tstate_storage.create;
         aktstate:=Tstate_storage.create;
         p.track_state_pass(true);
         p.track_state_pass(true);
             aktstate.free;
             aktstate.free;
+            aktstate := nil;
      end;
      end;
 {$endif}
 {$endif}
 
 

+ 13 - 5
compiler/pdecl.pas

@@ -210,6 +210,7 @@ implementation
           end;
           end;
         current_tokenpos:=storetokenpos;
         current_tokenpos:=storetokenpos;
         p.free;
         p.free;
+        p := nil;
         readconstant:=hp;
         readconstant:=hp;
       end;
       end;
 
 
@@ -484,7 +485,7 @@ implementation
               if not is_system_custom_attribute_descendant(od) then
               if not is_system_custom_attribute_descendant(od) then
                 begin
                 begin
                   incompatibletypes(od,class_tcustomattribute);
                   incompatibletypes(od,class_tcustomattribute);
-                  read_attr_paras.free;
+                  read_attr_paras.free; // no nil needed
                   continue;
                   continue;
                 end;
                 end;
 
 
@@ -555,8 +556,9 @@ implementation
                     begin
                     begin
                       { cleanup }
                       { cleanup }
                       pcalln.free;
                       pcalln.free;
+                      pcalln := nil;
                       for i:=0 to high(paras) do
                       for i:=0 to high(paras) do
-                        paras[i].free;
+                        FreeAndNil(paras[i]);
                     end;
                     end;
                 end
                 end
               else begin
               else begin
@@ -564,16 +566,18 @@ implementation
                 if errorcount=ecnt then
                 if errorcount=ecnt then
                   message(parser_e_illegal_expression);
                   message(parser_e_illegal_expression);
                 pcalln.free;
                 pcalln.free;
+                pcalln := nil;
               end;
               end;
             end
             end
           else
           else
             begin
             begin
               Message(type_e_type_id_expected);
               Message(type_e_type_id_expected);
               { try to recover by nevertheless reading the parameters (if any) }
               { try to recover by nevertheless reading the parameters (if any) }
-              read_attr_paras.free;
+              read_attr_paras.free; // no nil needed
             end;
             end;
 
 
           p.free;
           p.free;
+          p := nil;
         until not try_to_consume(_COMMA);
         until not try_to_consume(_COMMA);
 
 
         consume(_RECKKLAMMER);
         consume(_RECKKLAMMER);
@@ -949,6 +953,7 @@ implementation
                                   tstringdef(hdef).encoding:=int64(tordconstnode(p).value);
                                   tstringdef(hdef).encoding:=int64(tordconstnode(p).value);
                                 end;
                                 end;
                               p.free;
                               p.free;
+                              p := nil;
                             end;
                             end;
                           if (hdef.typ in [pointerdef,classrefdef]) and
                           if (hdef.typ in [pointerdef,classrefdef]) and
                              (tabstractpointerdef(hdef).pointeddef.typ=forwarddef) then
                              (tabstractpointerdef(hdef).pointeddef.typ=forwarddef) then
@@ -1205,11 +1210,12 @@ implementation
                  begin
                  begin
                    if (tstoredsym(generictypelist[i]).typ=typesym) and
                    if (tstoredsym(generictypelist[i]).typ=typesym) and
                        not ttypesym(generictypelist[i]).typedef.is_registered then
                        not ttypesym(generictypelist[i]).typedef.is_registered then
-                     ttypesym(generictypelist[i]).typedef.free;
+                     FreeAndNil(ttypesym(generictypelist[i]).typedef);
                    if not tstoredsym(generictypelist[i]).is_registered then
                    if not tstoredsym(generictypelist[i]).is_registered then
-                     tstoredsym(generictypelist[i]).free;
+                     tstoredsym(generictypelist[i]).free; // no nil needed
                  end;
                  end;
                generictypelist.free;
                generictypelist.free;
+               generictypelist := nil;
              end;
              end;
 
 
            if not (m_delphi in current_settings.modeswitches) and
            if not (m_delphi in current_settings.modeswitches) and
@@ -1254,6 +1260,7 @@ implementation
         rtti_attrs_def := nil;
         rtti_attrs_def := nil;
         types_dec(false,had_generic,rtti_attrs_def);
         types_dec(false,had_generic,rtti_attrs_def);
         rtti_attrs_def.free;
         rtti_attrs_def.free;
+        rtti_attrs_def := nil;
       end;
       end;
 
 
 
 
@@ -1402,6 +1409,7 @@ implementation
                      stringdispose(deprecatedmsg);
                      stringdispose(deprecatedmsg);
                    consume(_SEMICOLON);
                    consume(_SEMICOLON);
                    p.free;
                    p.free;
+                   p := nil;
                 end;
                 end;
               else
               else
                 if not first and isgeneric and
                 if not first and isgeneric and

+ 3 - 0
compiler/pdecobj.pas

@@ -423,6 +423,7 @@ implementation
         else
         else
           Message(parser_e_illegal_expression);
           Message(parser_e_illegal_expression);
         p.free;
         p.free;
+        p := nil;
       end;
       end;
 
 
     procedure get_cpp_or_java_class_external_status(od: tobjectdef);
     procedure get_cpp_or_java_class_external_status(od: tobjectdef);
@@ -1403,6 +1404,7 @@ implementation
                                     trtti_attribute_list.bind(rtti_attrs_def,tfieldvarsym(fieldlist[FldCount]).rtti_attribute_list)
                                     trtti_attribute_list.bind(rtti_attrs_def,tfieldvarsym(fieldlist[FldCount]).rtti_attribute_list)
                                   else
                                   else
                                     rtti_attrs_def.free;
                                     rtti_attrs_def.free;
+                                    rtti_attrs_def := nil;
                                   end;
                                   end;
                                 rtti_attrs_def:=nil;
                                 rtti_attrs_def:=nil;
                               end;
                               end;
@@ -1477,6 +1479,7 @@ implementation
         if is_class(current_structdef) then
         if is_class(current_structdef) then
           tabstractrecordsymtable(current_structdef.symtable).addfieldlist(fieldlist,true);
           tabstractrecordsymtable(current_structdef.symtable).addfieldlist(fieldlist,true);
         fieldlist.free;
         fieldlist.free;
+        fieldlist := nil;
       end;
       end;
 
 
 
 

+ 5 - 1
compiler/pdecsub.pas

@@ -334,7 +334,7 @@ implementation
             if assigned(vs.owner) then
             if assigned(vs.owner) then
              sc.add(vs)
              sc.add(vs)
             else
             else
-             vs.free;
+             vs.free; // no nil needed
             consume(_ID);
             consume(_ID);
           until not try_to_consume(_COMMA);
           until not try_to_consume(_COMMA);
           locationstr:='';
           locationstr:='';
@@ -528,6 +528,7 @@ implementation
 
 
         { remove parasymtable from stack }
         { remove parasymtable from stack }
         sc.free;
         sc.free;
+        sc := nil;
         { reset object options }
         { reset object options }
         block_type:=old_block_type;
         block_type:=old_block_type;
         consume(_RKLAMMER);
         consume(_RKLAMMER);
@@ -647,6 +648,7 @@ implementation
                       sym.typedef:=nil;
                       sym.typedef:=nil;
                     end;
                     end;
                   sym.free;
                   sym.free;
+                  sym := nil;
                 end;
                 end;
             genericparams.free;
             genericparams.free;
             genericparams:=nil;
             genericparams:=nil;
@@ -2091,6 +2093,7 @@ begin
   else
   else
     message(parser_e_dispid_must_be_ord_const);
     message(parser_e_dispid_must_be_ord_const);
   pt.free;
   pt.free;
+  pt := nil;
 end;
 end;
 
 
 
 
@@ -2201,6 +2204,7 @@ begin
      not objcvalidselectorname(@tprocdef(pd).messageinf.str^[1],length(tprocdef(pd).messageinf.str^)) then
      not objcvalidselectorname(@tprocdef(pd).messageinf.str^[1],length(tprocdef(pd).messageinf.str^)) then
     Message1(type_e_invalid_objc_selector_name,tprocdef(pd).messageinf.str^);
     Message1(type_e_invalid_objc_selector_name,tprocdef(pd).messageinf.str^);
   pt.free;
   pt.free;
+  pt := nil;
 end;
 end;
 
 
 
 

+ 17 - 5
compiler/pdecvar.pas

@@ -200,6 +200,7 @@ implementation
                              end;
                              end;
                             pl.addconst(sl_vec,idx,p.resultdef);
                             pl.addconst(sl_vec,idx,p.resultdef);
                             p.free;
                             p.free;
+                            p := nil;
                             def:=tarraydef(def).elementdef;
                             def:=tarraydef(def).elementdef;
                           end
                           end
                          else
                          else
@@ -306,6 +307,7 @@ implementation
                   else
                   else
                     Message(parser_e_dispid_must_be_ord_const);
                     Message(parser_e_dispid_must_be_ord_const);
                   pt.free;
                   pt.free;
+                  pt := nil;
                 end
                 end
               else
               else
                 hdispid:=tobjectdef(astruct).get_next_dispid;
                 hdispid:=tobjectdef(astruct).get_next_dispid;
@@ -435,6 +437,7 @@ implementation
                   tparavarsym(sc[i]).vardef:=hdef;
                   tparavarsym(sc[i]).vardef:=hdef;
               until not try_to_consume(_SEMICOLON);
               until not try_to_consume(_SEMICOLON);
               sc.free;
               sc.free;
+              sc := nil;
               symtablestack.pop(p.parast);
               symtablestack.pop(p.parast);
               consume(_RECKKLAMMER);
               consume(_RECKKLAMMER);
 
 
@@ -492,6 +495,7 @@ implementation
                    { concat a longint to the para templates }
                    { concat a longint to the para templates }
                    p.add_index_parameter(paranr,readprocdef,writeprocdef);
                    p.add_index_parameter(paranr,readprocdef,writeprocdef);
                    pt.free;
                    pt.free;
+                   pt := nil;
                 end;
                 end;
            end
            end
          else
          else
@@ -704,6 +708,7 @@ implementation
                   { Error recovery }
                   { Error recovery }
                   pt:=comp_expr([ef_accept_equal]);
                   pt:=comp_expr([ef_accept_equal]);
                   pt.free;
                   pt.free;
+                  pt := nil;
                 end
                 end
               else
               else
                 begin
                 begin
@@ -737,6 +742,7 @@ implementation
                       internalerror(2019050525);
                       internalerror(2019050525);
                   end;
                   end;
                   pt.free;
                   pt.free;
+                  pt := nil;
                 end;
                 end;
            end
            end
          else if not is_record(astruct) and try_to_consume(_NODEFAULT) then
          else if not is_record(astruct) and try_to_consume(_NODEFAULT) then
@@ -870,22 +876,22 @@ implementation
              if readprocdef.proctypeoption=potype_propgetter then
              if readprocdef.proctypeoption=potype_propgetter then
                readprocdef.register_def
                readprocdef.register_def
              else
              else
-               readprocdef.free;
+               readprocdef.free; // no nil needed
              if writeprocdef.proctypeoption=potype_propsetter then
              if writeprocdef.proctypeoption=potype_propsetter then
                writeprocdef.register_def
                writeprocdef.register_def
              else
              else
-               writeprocdef.free;
+               writeprocdef.free; // no nil needed
            end
            end
          else
          else
            begin
            begin
              if readprocdef.proctypeoption=potype_propgetter then
              if readprocdef.proctypeoption=potype_propgetter then
                readprocdef.maybe_put_in_symtable_stack
                readprocdef.maybe_put_in_symtable_stack
              else
              else
-               readprocdef.free;
+               readprocdef.free; // no nil needed
              if writeprocdef.proctypeoption=potype_propsetter then
              if writeprocdef.proctypeoption=potype_propsetter then
                writeprocdef.maybe_put_in_symtable_stack
                writeprocdef.maybe_put_in_symtable_stack
              else
              else
-               writeprocdef.free;
+               writeprocdef.free; // no nil needed
            end;
            end;
 
 
          result:=p;
          result:=p;
@@ -1152,6 +1158,7 @@ implementation
                     current_asmdata.asmlists[al_typedconsts].concatlist(templist);
                     current_asmdata.asmlists[al_typedconsts].concatlist(templist);
                   end;
                   end;
                 templist.free;
                 templist.free;
+                templist := nil;
               end;
               end;
             staticvarsym :
             staticvarsym :
               begin
               begin
@@ -1338,6 +1345,7 @@ implementation
                 Message(parser_e_absolute_only_to_var_or_const);
                 Message(parser_e_absolute_only_to_var_or_const);
             end;
             end;
           pt.free;
           pt.free;
+          pt := nil;
           { replace old varsym with the new absolutevarsym }
           { replace old varsym with the new absolutevarsym }
           if assigned(abssym) then
           if assigned(abssym) then
             begin
             begin
@@ -1419,6 +1427,7 @@ implementation
                    and (token in [_PROCEDURE,_FUNCTION,_CLASS]) then
                    and (token in [_PROCEDURE,_FUNCTION,_CLASS]) then
                  begin
                  begin
                    vs.free;
                    vs.free;
+                   vs := nil;
                    sc.clear;
                    sc.clear;
                    had_generic:=true;
                    had_generic:=true;
                    break;
                    break;
@@ -1635,6 +1644,7 @@ implementation
          block_type:=old_block_type;
          block_type:=old_block_type;
          { free the list }
          { free the list }
          sc.free;
          sc.free;
+         sc := nil;
       end;
       end;
 
 
 
 
@@ -1768,7 +1778,7 @@ implementation
                    had_generic:=false;
                    had_generic:=false;
                  end
                  end
                else
                else
-                 vs.free;
+                 vs.free; // no nil needed
              until not try_to_consume(_COMMA);
              until not try_to_consume(_COMMA);
              if m_delphi in current_settings.modeswitches then
              if m_delphi in current_settings.modeswitches then
                block_type:=bt_var_type
                block_type:=bt_var_type
@@ -2063,6 +2073,7 @@ implementation
                         end;
                         end;
                     end;
                     end;
                   pt.free;
                   pt.free;
+                  pt := nil;
                   if token=_COMMA then
                   if token=_COMMA then
                     consume(_COMMA)
                     consume(_COMMA)
                   else
                   else
@@ -2138,6 +2149,7 @@ implementation
            end;
            end;
          { free the list }
          { free the list }
          sc.free;
          sc.free;
+         sc := nil;
 {$ifdef powerpc}
 {$ifdef powerpc}
          is_first_type := false;
          is_first_type := false;
 {$endif powerpc}
 {$endif powerpc}

+ 2 - 0
compiler/pexports.pas

@@ -153,6 +153,7 @@ implementation
                         end;
                         end;
                        include(options,eo_index);
                        include(options,eo_index);
                        pt.free;
                        pt.free;
+                       pt := nil;
                        if target_info.system in [system_i386_win32,system_i386_wdosx,system_arm_wince,system_i386_wince] then
                        if target_info.system in [system_i386_win32,system_i386_wdosx,system_arm_wince,system_i386_wince] then
                         DefString:=srsym.realname+'='+InternalProcName+' @ '+tostr(index)
                         DefString:=srsym.realname+'='+InternalProcName+' @ '+tostr(index)
                        else
                        else
@@ -169,6 +170,7 @@ implementation
                          message(type_e_string_expr_expected);
                          message(type_e_string_expr_expected);
                        include(options,eo_name);
                        include(options,eo_name);
                        pt.free;
                        pt.free;
+                       pt := nil;
                        DefString:=hpname+'='+InternalProcName;
                        DefString:=hpname+'='+InternalProcName;
                      end;
                      end;
                     if try_to_consume(_RESIDENT) then
                     if try_to_consume(_RESIDENT) then

+ 26 - 5
compiler/pexpr.pas

@@ -138,6 +138,7 @@ implementation
                 consume(_RECKKLAMMER);
                 consume(_RECKKLAMMER);
               end;
               end;
              p.free;
              p.free;
+             p := nil;
            end
            end
           else
           else
             begin
             begin
@@ -424,6 +425,7 @@ implementation
                begin
                begin
                  Message(parser_e_class_id_expected);
                  Message(parser_e_class_id_expected);
                  p1.free;
                  p1.free;
+                 p1 := nil;
                  statement_syssym:=cerrornode.create;
                  statement_syssym:=cerrornode.create;
                end;
                end;
             end;
             end;
@@ -482,6 +484,7 @@ implementation
                     include(statement_syssym.flags,nf_generic_para);
                     include(statement_syssym.flags,nf_generic_para);
                  { p1 not needed !}
                  { p1 not needed !}
                  p1.free;
                  p1.free;
+                 p1 := nil;
                end;
                end;
             end;
             end;
 
 
@@ -605,6 +608,7 @@ implementation
               else
               else
                begin
                begin
                  p1.free;
                  p1.free;
+                 p1 := nil;
                  p2:=cerrornode.create;
                  p2:=cerrornode.create;
                end;
                end;
               consume(_RKLAMMER);
               consume(_RKLAMMER);
@@ -718,9 +722,9 @@ implementation
                   message(parser_e_illegal_slice);
                   message(parser_e_illegal_slice);
                   consume(_LKLAMMER);
                   consume(_LKLAMMER);
                   in_args:=true;
                   in_args:=true;
-                  comp_expr([ef_accept_equal]).free;
+                  comp_expr([ef_accept_equal]).free; // no nil needed
                   if try_to_consume(_COMMA) then
                   if try_to_consume(_COMMA) then
-                    comp_expr([ef_accept_equal]).free;
+                    comp_expr([ef_accept_equal]).free; // no nil needed
                   statement_syssym:=cerrornode.create;
                   statement_syssym:=cerrornode.create;
                   consume(_RKLAMMER);
                   consume(_RKLAMMER);
                 end
                 end
@@ -903,6 +907,7 @@ implementation
                   in_args:=true;
                   in_args:=true;
                   p1:=comp_expr([ef_accept_equal]);
                   p1:=comp_expr([ef_accept_equal]);
                   p1.free;
                   p1.free;
+                  p1 := nil;
                   consume(_RKLAMMER);
                   consume(_RKLAMMER);
                 end;
                 end;
               statement_syssym:=geninlinenode(l,false,nil);
               statement_syssym:=geninlinenode(l,false,nil);
@@ -1108,6 +1113,7 @@ implementation
                  comment(v_error, 'Pointers to generics functions not implemented');
                  comment(v_error, 'Pointers to generics functions not implemented');
                  p1:=cerrornode.create;
                  p1:=cerrornode.create;
                  spezcontext.free;
                  spezcontext.free;
+                 spezcontext := nil;
                  exit;
                  exit;
                end;
                end;
 
 
@@ -1161,7 +1167,7 @@ implementation
                         this is a "objectprocvar:[email protected]" expression }
                         this is a "objectprocvar:[email protected]" expression }
                       tloadnode(p2).symtable:=tobjectdef(p1.resultdef).symtable
                       tloadnode(p2).symtable:=tobjectdef(p1.resultdef).symtable
                     else
                     else
-                      p1.free;
+                      p1.free; // no nil needed
                   end;
                   end;
               end;
               end;
              p1:=p2;
              p1:=p2;
@@ -1254,6 +1260,7 @@ implementation
                  if (po_methodpointer in pv.procoptions) then
                  if (po_methodpointer in pv.procoptions) then
                    tloadnode(hp2).set_mp(tcallnode(hp).methodpointer.getcopy);
                    tloadnode(hp2).set_mp(tcallnode(hp).methodpointer.getcopy);
                  hp.free;
                  hp.free;
+                 hp := nil;
                  { replace the old callnode with the new loadnode }
                  { replace the old callnode with the new loadnode }
                  hpp^:=hp2;
                  hpp^:=hp2;
                end;
                end;
@@ -1293,6 +1300,7 @@ implementation
                begin
                begin
                  hp2:=cloadnode.create_procvar(tprocsym(tcallnode(hp).symtableprocentry),currprocdef,tcallnode(hp).symtableproc);
                  hp2:=cloadnode.create_procvar(tprocsym(tcallnode(hp).symtableprocentry),currprocdef,tcallnode(hp).symtableproc);
                  hp.free;
                  hp.free;
+                 hp := nil;
                  { replace the old callnode with the new loadnode }
                  { replace the old callnode with the new loadnode }
                  hpp^:=hp2;
                  hpp^:=hp2;
                end;
                end;
@@ -1440,7 +1448,7 @@ implementation
            end;
            end;
         { release paras if not used }
         { release paras if not used }
         if assigned(paras) then
         if assigned(paras) then
-         paras.free;
+          paras.free; // no nil needed
       end;
       end;
 
 
 
 
@@ -1461,6 +1469,7 @@ implementation
               p1:=cerrornode.create;
               p1:=cerrornode.create;
               { try to clean up }
               { try to clean up }
               spezcontext.free;
               spezcontext.free;
+              spezcontext := nil;
               again:=false;
               again:=false;
            end
            end
          else
          else
@@ -1793,8 +1802,10 @@ implementation
                    end;
                    end;
                  if result.nodetype<>errorn then
                  if result.nodetype<>errorn then
                    do_member_read(tabstractrecorddef(hdef),false,srsym,result,again,[],spezcontext)
                    do_member_read(tabstractrecorddef(hdef),false,srsym,result,again,[],spezcontext)
-                 else
+                 else begin
                    spezcontext.free;
                    spezcontext.free;
+                   spezcontext := nil;
+                 end;
                end
                end
              else
              else
               begin
               begin
@@ -2028,6 +2039,7 @@ implementation
            end;
            end;
          countindices:=elements.count;
          countindices:=elements.count;
          elements.free;
          elements.free;
+         elements := nil;
 
 
          consume(_RECKKLAMMER);
          consume(_RECKKLAMMER);
 
 
@@ -3130,6 +3142,7 @@ implementation
                          if not handle_specialize_inline_specialization(srsym,unit_found,srsymtable,spezcontext) or (srsym.typ=procsym) then
                          if not handle_specialize_inline_specialization(srsym,unit_found,srsymtable,spezcontext) or (srsym.typ=procsym) then
                            begin
                            begin
                              spezcontext.free;
                              spezcontext.free;
+                             spezcontext := nil;
                              result:=cerrornode.create;
                              result:=cerrornode.create;
                              if try_to_consume(_LKLAMMER) then
                              if try_to_consume(_LKLAMMER) then
                               begin
                               begin
@@ -3292,6 +3305,7 @@ implementation
               result.resultdef:=cundefineddef.create(true);
               result.resultdef:=cundefineddef.create(true);
               { clean up previously created dummy symbol }
               { clean up previously created dummy symbol }
               srsym.free;
               srsym.free;
+              srsym := nil;
             end;
             end;
 
 
           errorsym :
           errorsym :
@@ -3987,7 +4001,10 @@ implementation
                            do_member_read(hclassdef,getaddr,srsym,p1,again,callflags,spezcontext);
                            do_member_read(hclassdef,getaddr,srsym,p1,again,callflags,spezcontext);
                          end;
                          end;
                        if p1.nodetype=errorn then
                        if p1.nodetype=errorn then
+                       begin
                          spezcontext.free;
                          spezcontext.free;
+                         spezcontext := nil;
+                       end;
                      end
                      end
                     else
                     else
                      begin
                      begin
@@ -4645,6 +4662,7 @@ implementation
               result:=cerrornode.create;
               result:=cerrornode.create;
 
 
           spezcontext.free;
           spezcontext.free;
+          spezcontext := nil;
         end;
         end;
 
 
       function maybe_handle_specialization(var p1,p2:tnode;filepos:tfileposinfo):boolean;
       function maybe_handle_specialization(var p1,p2:tnode;filepos:tfileposinfo):boolean;
@@ -4687,6 +4705,7 @@ implementation
               { we don't need these nodes anymore }
               { we don't need these nodes anymore }
               p1.free;
               p1.free;
               p2.free;
               p2.free;
+              p2 := nil;
 
 
               p1:=ptmp;
               p1:=ptmp;
 
 
@@ -5073,6 +5092,7 @@ implementation
           result:=tordconstnode(p).value;
           result:=tordconstnode(p).value;
        end;
        end;
       p.free;
       p.free;
+      p := nil;
     end;
     end;
 
 
 
 
@@ -5110,6 +5130,7 @@ implementation
       else
       else
         get_stringconst:=snode.asrawbytestring;
         get_stringconst:=snode.asrawbytestring;
       p.free;
       p.free;
+      p := nil;
     end;
     end;
 
 
 end.
 end.

+ 1 - 0
compiler/pgentype.pas

@@ -72,6 +72,7 @@ end;
 destructor tspecializationcontext.destroy;
 destructor tspecializationcontext.destroy;
 begin
 begin
   paramlist.free;
   paramlist.free;
+  paramlist := nil;
   tfplist.FreeAndNilDisposing(poslist,TypeInfo(tfileposinfo));
   tfplist.FreeAndNilDisposing(poslist,TypeInfo(tfileposinfo));
   inherited destroy;
   inherited destroy;
 end;
 end;

+ 26 - 3
compiler/pgenutil.pas

@@ -646,6 +646,7 @@ uses
                 result:=false;
                 result:=false;
               end;
               end;
             typeparam.free;
             typeparam.free;
+            typeparam := nil;
             first:=false;
             first:=false;
           end;
           end;
         block_type:=old_block_type;
         block_type:=old_block_type;
@@ -673,7 +674,7 @@ uses
           genericdef:=tstoreddef(generate_specialization_phase2(context,genericdef,parse_class_parent,_prettyname));
           genericdef:=tstoreddef(generate_specialization_phase2(context,genericdef,parse_class_parent,_prettyname));
         tt:=genericdef;
         tt:=genericdef;
         if assigned(context) then
         if assigned(context) then
-          context.free;
+          context.free; // no nil needed
       end;
       end;
 
 
 
 
@@ -1033,6 +1034,7 @@ uses
               if compare_defs(caller_proc_para.vardef,target_proc_para.vardef,nothingn)=te_incompatible then
               if compare_defs(caller_proc_para.vardef,target_proc_para.vardef,nothingn)=te_incompatible then
                 begin
                 begin
                   newparams.free;
                   newparams.free;
+                  newparams := nil;
                   exit(false);
                   exit(false);
                 end;
                 end;
 
 
@@ -1055,6 +1057,7 @@ uses
               if compare_defs(caller_proc.returndef,target_proc.returndef,nothingn)<te_equal then
               if compare_defs(caller_proc.returndef,target_proc.returndef,nothingn)<te_equal then
                 begin
                 begin
                   newparams.free;
                   newparams.free;
+                  newparams := nil;
                   exit(false);
                   exit(false);
                 end;
                 end;
 
 
@@ -1072,6 +1075,7 @@ uses
               genericparams.add(newparams.nameofindex(i),newparams[i]);
               genericparams.add(newparams.nameofindex(i),newparams[i]);
 
 
           newparams.free;
           newparams.free;
+          newparams := nil;
         end;
         end;
 
 
       function maybe_inherited_specialization(givendef,desireddef:tstoreddef;out basedef:tstoreddef):boolean;
       function maybe_inherited_specialization(givendef,desireddef:tstoreddef;out basedef:tstoreddef):boolean;
@@ -1147,6 +1151,7 @@ uses
           if callerparams.count<required_param_count then
           if callerparams.count<required_param_count then
             begin
             begin
               paras.free;
               paras.free;
+              paras := nil;
               exit;
               exit;
             end;
             end;
 
 
@@ -1160,6 +1165,7 @@ uses
           if count<genericdef.genericparas.count then
           if count<genericdef.genericparas.count then
             begin
             begin
               paras.free;
               paras.free;
+              paras := nil;
               exit;
               exit;
             end;
             end;
 
 
@@ -1172,7 +1178,9 @@ uses
               if i=paras.count then
               if i=paras.count then
                 begin
                 begin
                   genericparams.free;
                   genericparams.free;
+                  genericparams := nil;
                   paras.free;
                   paras.free;
+                  paras := nil;
                   exit;
                   exit;
                 end;
                 end;
 
 
@@ -1261,8 +1269,11 @@ uses
 
 
           { cleanup }
           { cleanup }
           paras.free;
           paras.free;
-          if not result then
+          paras := nil;
+          if not result then begin
             genericparams.free;
             genericparams.free;
+            genericparams := nil;
+          end;
         end;
         end;
 
 
       { make an ordered list of parameters from the caller }
       { make an ordered list of parameters from the caller }
@@ -1323,10 +1334,12 @@ uses
                   begin
                   begin
                     generate_implicit_specialization(spezcontext,pd,genericparams);
                     generate_implicit_specialization(spezcontext,pd,genericparams);
                     genericparams.free;
                     genericparams.free;
+                    genericparams := nil;
                     { finalize the specialization so it can be added to the list of overloads }
                     { finalize the specialization so it can be added to the list of overloads }
                     if not finalize_specialization(pd,spezcontext) then
                     if not finalize_specialization(pd,spezcontext) then
                       begin
                       begin
                         spezcontext.free;
                         spezcontext.free;
+                        spezcontext := nil;
                         continue;
                         continue;
                       end;
                       end;
                     { handle unnamed syms used by the specialization }
                     { handle unnamed syms used by the specialization }
@@ -1334,9 +1347,11 @@ uses
                       begin
                       begin
                         transfer_unnamed_symbols(pd.owner,pd_unnamed_syms);
                         transfer_unnamed_symbols(pd.owner,pd_unnamed_syms);
                         pd_unnamed_syms.free;
                         pd_unnamed_syms.free;
+                        pd_unnamed_syms := nil;
                       end;
                       end;
                     pdoverloadlist.add(pd);
                     pdoverloadlist.add(pd);
                     spezcontext.free;
                     spezcontext.free;
+                    spezcontext := nil;
                     if po_overload in pd.procoptions then
                     if po_overload in pd.procoptions then
                       hasoverload:=true;
                       hasoverload:=true;
                     { store first procsym found }
                     { store first procsym found }
@@ -1363,6 +1378,7 @@ uses
           end;
           end;
 
 
         callerparams.free;
         callerparams.free;
+        callerparams := nil;
       end;
       end;
 
 
     function generate_specialization_phase1(out context:tspecializationcontext;genericdef:tdef;enforce_unit:boolean):tdef;
     function generate_specialization_phase1(out context:tspecializationcontext;genericdef:tdef;enforce_unit:boolean):tdef;
@@ -1558,6 +1574,7 @@ uses
             for i:=tmpstack.count-1 downto 0 do
             for i:=tmpstack.count-1 downto 0 do
               symtablestack.push(tsymtable(tmpstack[i]));
               symtablestack.push(tsymtable(tmpstack[i]));
             tmpstack.free;
             tmpstack.free;
+            tmpstack := nil;
           end;
           end;
 
 
         if not found or not (context.sym.typ in [typesym,procsym]) then
         if not found or not (context.sym.typ in [typesym,procsym]) then
@@ -2196,6 +2213,7 @@ uses
               specializest.includeoption(sto_has_generic);
               specializest.includeoption(sto_has_generic);
 
 
             tempst.free;
             tempst.free;
+            tempst := nil;
 
 
             specialization_done(state);
             specialization_done(state);
 
 
@@ -2206,6 +2224,7 @@ uses
           end;
           end;
 
 
         generictypelist.free;
         generictypelist.free;
+        generictypelist := nil;
         if assigned(genericdef) then
         if assigned(genericdef) then
           begin
           begin
             { check the hints of the found generic symbol }
             { check the hints of the found generic symbol }
@@ -2228,7 +2247,7 @@ uses
           genericdef:=tstoreddef(generate_specialization_phase2(context,genericdef,parse_class_parent,_prettyname));
           genericdef:=tstoreddef(generate_specialization_phase2(context,genericdef,parse_class_parent,_prettyname));
         tt:=genericdef;
         tt:=genericdef;
         if assigned(context) then
         if assigned(context) then
-          context.free;
+          context.free; // no nil needed
       end;
       end;
 
 
 
 
@@ -2446,6 +2465,7 @@ uses
               firstidx:=result.count;
               firstidx:=result.count;
 
 
               constraintdata.free;
               constraintdata.free;
+              constraintdata := nil;
             end
             end
           else
           else
             begin
             begin
@@ -2854,6 +2874,7 @@ uses
           pu:=tused_unit(pu.next);
           pu:=tused_unit(pu.next);
         end;
         end;
       unitsyms.free;
       unitsyms.free;
+      unitsyms := nil;
       if assigned(hmodule.globalsymtable) then
       if assigned(hmodule.globalsymtable) then
         symtablestack.push(hmodule.globalsymtable);
         symtablestack.push(hmodule.globalsymtable);
       symtable:=genericdef.owner;
       symtable:=genericdef.owner;
@@ -3043,7 +3064,9 @@ uses
           current_module.pendingspecializations.add(tstoreddef(readdlist[i]).typename,readdlist[i]);
           current_module.pendingspecializations.add(tstoreddef(readdlist[i]).typename,readdlist[i]);
 
 
         readdlist.free;
         readdlist.free;
+        readdlist := nil;
         list.free;
         list.free;
+        list := nil;
       end;
       end;
 
 
 
 

+ 12 - 0
compiler/pinline.pas

@@ -166,8 +166,10 @@ implementation
             if not(assigned(sym)) then
             if not(assigned(sym)) then
               begin
               begin
                  p.free;
                  p.free;
+                 p := nil;
                  if is_new then
                  if is_new then
                    p2.free;
                    p2.free;
+                   p2 := nil;
                  new_dispose_statement := cerrornode.create;
                  new_dispose_statement := cerrornode.create;
                  consume_all_until(_RKLAMMER);
                  consume_all_until(_RKLAMMER);
                  consume(_RKLAMMER);
                  consume(_RKLAMMER);
@@ -218,6 +220,7 @@ implementation
                  p.free;
                  p.free;
                  p:=factor(false,[]);
                  p:=factor(false,[]);
                  p.free;
                  p.free;
+                 p := nil;
                  consume(_RKLAMMER);
                  consume(_RKLAMMER);
                  new_dispose_statement:=cnothingnode.create;
                  new_dispose_statement:=cnothingnode.create;
                  exit;
                  exit;
@@ -229,6 +232,7 @@ implementation
                  p.free;
                  p.free;
                  p:=factor(false,[]);
                  p:=factor(false,[]);
                  p.free;
                  p.free;
+                 p := nil;
                  consume(_RKLAMMER);
                  consume(_RKLAMMER);
                  new_dispose_statement:=cerrornode.create;
                  new_dispose_statement:=cerrornode.create;
                  exit;
                  exit;
@@ -238,6 +242,7 @@ implementation
               begin
               begin
                  Message(parser_e_pointer_to_class_expected);
                  Message(parser_e_pointer_to_class_expected);
                  p.free;
                  p.free;
+                 p := nil;
                  new_dispose_statement:=factor(false,[]);
                  new_dispose_statement:=factor(false,[]);
                  consume_all_until(_RKLAMMER);
                  consume_all_until(_RKLAMMER);
                  consume(_RKLAMMER);
                  consume(_RKLAMMER);
@@ -268,6 +273,7 @@ implementation
                  else
                  else
                   Message(parser_e_expr_have_to_be_destructor_call);
                   Message(parser_e_expr_have_to_be_destructor_call);
                  p.free;
                  p.free;
+                 p := nil;
                  new_dispose_statement:=cerrornode.create;
                  new_dispose_statement:=cerrornode.create;
               end
               end
             else
             else
@@ -345,6 +351,7 @@ implementation
                  if is_typeparam(p.resultdef) then
                  if is_typeparam(p.resultdef) then
                    begin
                    begin
                       p.free;
                       p.free;
+                      p := nil;
                       consume(_RKLAMMER);
                       consume(_RKLAMMER);
                       new_dispose_statement:=cnothingnode.create;
                       new_dispose_statement:=cnothingnode.create;
                       exit;
                       exit;
@@ -452,6 +459,7 @@ implementation
            consume_all_until(_RKLAMMER);
            consume_all_until(_RKLAMMER);
            consume(_RKLAMMER);
            consume(_RKLAMMER);
            p1.free;
            p1.free;
+           p1 := nil;
            new_function:=cerrornode.create;
            new_function:=cerrornode.create;
            exit;
            exit;
          end;
          end;
@@ -462,6 +470,7 @@ implementation
            consume_all_until(_RKLAMMER);
            consume_all_until(_RKLAMMER);
            consume(_RKLAMMER);
            consume(_RKLAMMER);
            p1.free;
            p1.free;
+           p1 := nil;
            new_function:=cerrornode.create;
            new_function:=cerrornode.create;
            exit;
            exit;
          end;
          end;
@@ -486,6 +495,7 @@ implementation
                consume_all_until(_RKLAMMER);
                consume_all_until(_RKLAMMER);
                consume(_RKLAMMER);
                consume(_RKLAMMER);
                p1.free;
                p1.free;
+               p1 := nil;
                new_function:=cerrornode.create;
                new_function:=cerrornode.create;
                exit;
                exit;
              end;
              end;
@@ -512,6 +522,7 @@ implementation
               the pointer to the object }
               the pointer to the object }
             p1.resultdef:=p2.resultdef;
             p1.resultdef:=p2.resultdef;
             p2.free;
             p2.free;
+            p2 := nil;
             consume(_RKLAMMER);
             consume(_RKLAMMER);
           end;
           end;
         new_function:=p1;
         new_function:=p1;
@@ -643,6 +654,7 @@ implementation
          end;
          end;
         ppn.left:=nil;
         ppn.left:=nil;
         paras.free;
         paras.free;
+        paras := nil;
         result.free;
         result.free;
         result:=newblock;
         result:=newblock;
       end;
       end;

+ 11 - 0
compiler/pkgutil.pas

@@ -286,6 +286,7 @@ implementation
       if not inppu.openfile then
       if not inppu.openfile then
        begin
        begin
          inppu.free;
          inppu.free;
+         inppu := nil;
          Comment(V_Error,'Could not open : '+PPUFn);
          Comment(V_Error,'Could not open : '+PPUFn);
          Exit;
          Exit;
        end;
        end;
@@ -293,6 +294,7 @@ implementation
       if not inppu.CheckPPUId then
       if not inppu.CheckPPUId then
        begin
        begin
          inppu.free;
          inppu.free;
+         inppu := nil;
          Comment(V_Error,'Not a PPU File : '+PPUFn);
          Comment(V_Error,'Not a PPU File : '+PPUFn);
          Exit;
          Exit;
        end;
        end;
@@ -300,6 +302,7 @@ implementation
       if ppuversion<>CurrentPPUVersion then
       if ppuversion<>CurrentPPUVersion then
        begin
        begin
          inppu.free;
          inppu.free;
+         inppu := nil;
          Comment(V_Error,'Wrong PPU Version '+tostr(ppuversion)+' in '+PPUFn);
          Comment(V_Error,'Wrong PPU Version '+tostr(ppuversion)+' in '+PPUFn);
          Exit;
          Exit;
        end;
        end;
@@ -307,6 +310,7 @@ implementation
       if (inppu.header.common.flags and uf_in_library)<>0 then
       if (inppu.header.common.flags and uf_in_library)<>0 then
        begin
        begin
          inppu.free;
          inppu.free;
+         inppu := nil;
          Comment(V_Error,'PPU is already in a library : '+PPUFn);
          Comment(V_Error,'PPU is already in a library : '+PPUFn);
          Exit;
          Exit;
        end;
        end;
@@ -314,6 +318,7 @@ implementation
       if (inppu.header.common.flags and (uf_static_linked or uf_no_link))=0 then
       if (inppu.header.common.flags and (uf_static_linked or uf_no_link))=0 then
        begin
        begin
          inppu.free;
          inppu.free;
+         inppu := nil;
          Comment(V_Error,'PPU is not static linked : '+PPUFn);
          Comment(V_Error,'PPU is not static linked : '+PPUFn);
          Exit;
          Exit;
        end;
        end;
@@ -340,7 +345,9 @@ implementation
         if b in [ibendinterface,ibend] then
         if b in [ibendinterface,ibend] then
          begin
          begin
            inppu.free;
            inppu.free;
+           inppu := nil;
            outppu.free;
            outppu.free;
+           outppu := nil;
            Comment(V_Error,'No files to be linked found : '+PPUFn);
            Comment(V_Error,'No files to be linked found : '+PPUFn);
            Exit;
            Exit;
          end;
          end;
@@ -438,7 +445,9 @@ implementation
       outppu.flush;
       outppu.flush;
       outppu.writeheader;
       outppu.writeheader;
       outppu.free;
       outppu.free;
+      outppu := nil;
       inppu.free;
       inppu.free;
+      inppu := nil;
       Result:=True;
       Result:=True;
     end;
     end;
 
 
@@ -866,9 +875,11 @@ implementation
         end;
         end;
 
 
       alreadyloaded.free;
       alreadyloaded.free;
+      alreadyloaded := nil;
       for i:=0 to cache.count-1 do
       for i:=0 to cache.count-1 do
         dispose(pcacheentry(cache[i]));
         dispose(pcacheentry(cache[i]));
       cache.free;
       cache.free;
+      cache := nil;
     end;
     end;
 
 
 
 

+ 10 - 0
compiler/pmodules.pas

@@ -82,6 +82,7 @@ implementation
                KeepShared.Concat(s);
                KeepShared.Concat(s);
             end;
             end;
            DLLscanner.Free;
            DLLscanner.Free;
+           DLLscanner := nil;
            { Recreate import section }
            { Recreate import section }
            if (target_info.system in [system_i386_win32,system_i386_wdosx]) then
            if (target_info.system in [system_i386_win32,system_i386_wdosx]) then
             begin
             begin
@@ -98,6 +99,7 @@ implementation
               curr.linkOtherSharedLibs.add(s,link_always);
               curr.linkOtherSharedLibs.add(s,link_always);
             end;
             end;
            KeepShared.Free;
            KeepShared.Free;
+           KeepShared := nil;
          end;
          end;
 
 
         { allow a target-specific pass over all assembler code (used by LLVM
         { allow a target-specific pass over all assembler code (used by LLVM
@@ -311,6 +313,7 @@ implementation
               internalerror(2024020701);
               internalerror(2024020701);
             curr.used_units.Remove(uu);
             curr.used_units.Remove(uu);
             uu.Free;
             uu.Free;
+            uu := nil;
            { remove the module }
            { remove the module }
             loaded_units.Remove(hp);
             loaded_units.Remove(hp);
             unloaded_units.Concat(hp);
             unloaded_units.Concat(hp);
@@ -711,6 +714,7 @@ implementation
                 current_scanner.tempopeninputfile;
                 current_scanner.tempopeninputfile;
               end;
               end;
            state.free;
            state.free;
+           state := nil;
          end;
          end;
 
 
       begin
       begin
@@ -2164,6 +2168,7 @@ type
              Message1(unit_f_errors_in_unit,tostr(Errorcount));
              Message1(unit_f_errors_in_unit,tostr(Errorcount));
              status.skip_error:=true;
              status.skip_error:=true;
              pkg.free;
              pkg.free;
+             pkg := nil;
              exit;
              exit;
            end;
            end;
 
 
@@ -2245,6 +2250,7 @@ type
             Message1(unit_f_errors_in_unit,tostr(Errorcount));
             Message1(unit_f_errors_in_unit,tostr(Errorcount));
             status.skip_error:=true;
             status.skip_error:=true;
             pkg.free;
             pkg.free;
+            pkg := nil;
             exit;
             exit;
           end;
           end;
 
 
@@ -2304,6 +2310,7 @@ type
                       begin
                       begin
                         loaded_units.remove(hp);
                         loaded_units.remove(hp);
                         hp.free;
                         hp.free;
+                        hp := nil;
                       end;
                       end;
                     hp:=hp2;
                     hp:=hp2;
                   end;
                   end;
@@ -2321,6 +2328,7 @@ type
               end;
               end;
 
 
              pkg.free;
              pkg.free;
+             pkg := nil;
           end;
           end;
       end;
       end;
 
 
@@ -2362,6 +2370,7 @@ type
                  begin
                  begin
                    loaded_units.remove(hp);
                    loaded_units.remove(hp);
                    hp.free;
                    hp.free;
+                   hp := nil;
                  end;
                  end;
                hp:=hp2;
                hp:=hp2;
              end;
              end;
@@ -2616,6 +2625,7 @@ type
                call_through_new_name(main_procinfo.procdef,target_info.cprefix+'FPC_LIBMAIN');
                call_through_new_name(main_procinfo.procdef,target_info.cprefix+'FPC_LIBMAIN');
                initpd:=main_procinfo.procdef;
                initpd:=main_procinfo.procdef;
                main_procinfo.free;
                main_procinfo.free;
+               main_procinfo := nil;
              end;
              end;
 
 
            main_procinfo:=create_main_proc(make_mangledname('',curr.localsymtable,mainaliasname),potype_proginit,curr.localsymtable);
            main_procinfo:=create_main_proc(make_mangledname('',curr.localsymtable,mainaliasname),potype_proginit,curr.localsymtable);

+ 5 - 2
compiler/procdefutil.pas

@@ -700,6 +700,7 @@ implementation
             end;
             end;
         end;
         end;
       symstodo.free;
       symstodo.free;
+      symstodo := nil;
     end;
     end;
 
 
 
 
@@ -1728,10 +1729,12 @@ implementation
             end;
             end;
 
 
           tocapture.free;
           tocapture.free;
+          tocapture := nil;
         end;
         end;
 
 
       { not required anymore }
       { not required anymore }
       capturedsyms.free;
       capturedsyms.free;
+      capturedsyms := nil;
 
 
       if convertarg.mappings.count>0 then
       if convertarg.mappings.count>0 then
         foreachnodestatic(pm_postprocess,tree,@convert_captured_sym,@convertarg);
         foreachnodestatic(pm_postprocess,tree,@convert_captured_sym,@convertarg);
@@ -1739,11 +1742,11 @@ implementation
       for i:=0 to convertarg.mappings.count-1 do
       for i:=0 to convertarg.mappings.count-1 do
         begin
         begin
           mapping:=pconvert_mapping(convertarg.mappings[i]);
           mapping:=pconvert_mapping(convertarg.mappings[i]);
-          mapping^.selfnode.free;
+          mapping^.selfnode.free; // no nil needed
           dispose(mapping);
           dispose(mapping);
         end;
         end;
 
 
-      convertarg.mappings.free;
+      convertarg.mappings.free; // no nil needed
     end;
     end;
 
 
 
 

+ 6 - 0
compiler/procinfo.pas

@@ -264,10 +264,15 @@ implementation
     destructor tprocinfo.destroy;
     destructor tprocinfo.destroy;
       begin
       begin
          nestedprocs.free;
          nestedprocs.free;
+         nestedprocs := nil;
          aktproccode.free;
          aktproccode.free;
+         aktproccode := nil;
          aktlocaldata.free;
          aktlocaldata.free;
+         aktlocaldata := nil;
          localrefsyms.free;
          localrefsyms.free;
+         localrefsyms := nil;
          localrefdefs.free;
          localrefdefs.free;
+         localrefdefs := nil;
       end;
       end;
 
 
     procedure tprocinfo.destroy_tree;
     procedure tprocinfo.destroy_tree;
@@ -278,6 +283,7 @@ implementation
         while Assigned(hp.parent) do
         while Assigned(hp.parent) do
           hp:=hp.parent;
           hp:=hp.parent;
         hp.Free;
         hp.Free;
+        hp := nil;
       end;
       end;
 
 
     procedure tprocinfo.addnestedproc(child: tprocinfo);
     procedure tprocinfo.addnestedproc(child: tprocinfo);

+ 7 - 0
compiler/psabiehpi.pas

@@ -183,6 +183,7 @@ implementation
         if not(actionlist.Empty) then
         if not(actionlist.Empty) then
           Internalerror(2019020501);
           Internalerror(2019020501);
         actionlist.Free;
         actionlist.Free;
+        actionlist := nil;
         inherited Destroy;
         inherited Destroy;
       end;
       end;
 
 
@@ -226,11 +227,17 @@ implementation
     destructor tpsabiehprocinfo.destroy;
     destructor tpsabiehprocinfo.destroy;
       begin
       begin
          gcc_except_table_data.free;
          gcc_except_table_data.free;
+         gcc_except_table_data := nil;
          actionstack.free;
          actionstack.free;
+         actionstack := nil;
          landingpadstack.free;
          landingpadstack.free;
+         landingpadstack := nil;
          typefilterlist.free;
          typefilterlist.free;
+         typefilterlist := nil;
          callsite_table_data.Free;
          callsite_table_data.Free;
+         callsite_table_data := nil;
          action_table_data.Free;
          action_table_data.Free;
+         action_table_data := nil;
          inherited;
          inherited;
       end;
       end;
 
 

+ 13 - 1
compiler/pstatmnt.pas

@@ -259,8 +259,11 @@ implementation
                    end;
                    end;
                end;
                end;
              p.free;
              p.free;
+             p := nil;
              sl1.free;
              sl1.free;
+             sl1 := nil;
              sl2.free;
              sl2.free;
+             sl2 := nil;
 
 
              if token=_COMMA then
              if token=_COMMA then
                consume(_COMMA)
                consume(_COMMA)
@@ -548,6 +551,7 @@ implementation
               result:=create_for_in_loop(hloopvar,hloopbody,expr);
               result:=create_for_in_loop(hloopvar,hloopbody,expr);
 
 
               expr.free;
               expr.free;
+              expr := nil;
             end;
             end;
 
 
 
 
@@ -791,6 +795,7 @@ implementation
             for i:=withsymtablelist.count-1 downto 0 do
             for i:=withsymtablelist.count-1 downto 0 do
               symtablestack.pop(TSymtable(withsymtablelist[i]));
               symtablestack.pop(TSymtable(withsymtablelist[i]));
             withsymtablelist.free;
             withsymtablelist.free;
+            withsymtablelist := nil;
 
 
             { Finalize complex withnode with destroy of temp }
             { Finalize complex withnode with destroy of temp }
             if assigned(newblock) then
             if assigned(newblock) then
@@ -807,6 +812,7 @@ implementation
          else
          else
           begin
           begin
             p.free;
             p.free;
+            p := nil;
             Message1(parser_e_false_with_expr,p.resultdef.GetTypeName);
             Message1(parser_e_false_with_expr,p.resultdef.GetTypeName);
             { try to recover from error }
             { try to recover from error }
             if try_to_consume(_COMMA) then
             if try_to_consume(_COMMA) then
@@ -1031,7 +1037,10 @@ implementation
                        begin
                        begin
                          symtablestack.pop(excepTSymtable);
                          symtablestack.pop(excepTSymtable);
                          if last.nodetype <> onn then
                          if last.nodetype <> onn then
-                           excepTSymtable.free;
+                           begin
+                             excepTSymtable.free;
+                             excepTSymtable := nil;
+                           end;
                        end;
                        end;
                      if not try_to_consume(_SEMICOLON) then
                      if not try_to_consume(_SEMICOLON) then
                         break;
                         break;
@@ -1087,6 +1096,7 @@ implementation
              asmstat:=casmnode.create(hl);
              asmstat:=casmnode.create(hl);
              asmstat.fileinfo:=entrypos;
              asmstat.fileinfo:=entrypos;
              asmreader.free;
              asmreader.free;
+             asmreader := nil;
            end
            end
          else
          else
            Message(parser_f_assembler_reader_not_supported);
            Message(parser_f_assembler_reader_not_supported);
@@ -1310,6 +1320,7 @@ implementation
             consume(_RKLAMMER); {error}
             consume(_RKLAMMER); {error}
         until nesting<0;
         until nesting<0;
         tokenbuf.free;
         tokenbuf.free;
+        tokenbuf := nil;
         { mark boundaries of assembler block, this is necessary for optimizer }
         { mark boundaries of assembler block, this is necessary for optimizer }
         hl.insert(tai_marker.create(mark_asmblockstart));
         hl.insert(tai_marker.create(mark_asmblockstart));
         hl.concat(tai_marker.create(mark_asmblockend));
         hl.concat(tai_marker.create(mark_asmblockend));
@@ -1473,6 +1484,7 @@ implementation
                 else
                 else
                   searchsym(s,srsym,srsymtable);
                   searchsym(s,srsym,srsymtable);
                 p.free;
                 p.free;
+                p := nil;
 
 
                 if assigned(srsym) and
                 if assigned(srsym) and
                    (srsym.typ=labelsym) then
                    (srsym.typ=labelsym) then

+ 5 - 0
compiler/psub.pas

@@ -688,6 +688,7 @@ implementation
        begin
        begin
          TFPList.FreeAndNilDisposing(tempinfo_flags_map,TypeInfo(ttempinfo_flags_entry));
          TFPList.FreeAndNilDisposing(tempinfo_flags_map,TypeInfo(ttempinfo_flags_entry));
          code.free;
          code.free;
+         code := nil;
          inherited destroy;
          inherited destroy;
        end;
        end;
 
 
@@ -1412,6 +1413,7 @@ implementation
         nodeset:=THashSet.Create(32,false,false);
         nodeset:=THashSet.Create(32,false,false);
         foreachnode(code,@store_node_tempflags,nodeset);
         foreachnode(code,@store_node_tempflags,nodeset);
         nodeset.free;
         nodeset.free;
+        nodeset := nil;
       end;
       end;
 
 
 
 
@@ -1869,6 +1871,7 @@ implementation
                 begin
                 begin
                   aktproccode.remove(ai);
                   aktproccode.remove(ai);
                   ai.free;
                   ai.free;
+                  ai := nil;
                   anode.currenttai:=nil;
                   anode.currenttai:=nil;
                 end;
                 end;
             end;
             end;
@@ -2343,12 +2346,14 @@ implementation
           end;
           end;
 
 
         dfabuilder.free;
         dfabuilder.free;
+        dfabuilder := nil;
 
 
         { restore symtablestack }
         { restore symtablestack }
         remove_from_symtablestack;
         remove_from_symtablestack;
 
 
         { restore }
         { restore }
         templist.free;
         templist.free;
+        templist := nil;
         current_settings.maxfpuregisters:=oldmaxfpuregisters;
         current_settings.maxfpuregisters:=oldmaxfpuregisters;
         current_filepos:=oldfilepos;
         current_filepos:=oldfilepos;
         current_structdef:=old_current_structdef;
         current_structdef:=old_current_structdef;

+ 1 - 0
compiler/ptconst.pas

@@ -146,6 +146,7 @@ implementation
           end;
           end;
 
 
         tcbuilder.free;
         tcbuilder.free;
+        tcbuilder := nil;
         current_filepos:=storefilepos;
         current_filepos:=storefilepos;
       end;
       end;
 
 

+ 6 - 0
compiler/ptype.pas

@@ -149,6 +149,7 @@ implementation
                      searchsym(upper(hs),srsym,srsymtable);
                      searchsym(upper(hs),srsym,srsymtable);
                      { we don't need the forwarddef anymore, dispose it }
                      { we don't need the forwarddef anymore, dispose it }
                      hpd.free;
                      hpd.free;
+                     hpd := nil;
                      tabstractpointerdef(def).pointeddef:=nil; { if error occurs }
                      tabstractpointerdef(def).pointeddef:=nil; { if error occurs }
                      { was a type sym found ? }
                      { was a type sym found ? }
                      if assigned(srsym) and
                      if assigned(srsym) and
@@ -341,6 +342,7 @@ implementation
                    end;
                    end;
                  parse_nested_types(def,isfowarddef,true,structdefstack);
                  parse_nested_types(def,isfowarddef,true,structdefstack);
                  structdefstack.free;
                  structdefstack.free;
+                 structdefstack := nil;
                  result:=true;
                  result:=true;
                  exit;
                  exit;
                end;
                end;
@@ -1270,6 +1272,7 @@ implementation
                else
                else
                  Message(sym_e_error_in_type_def);
                  Message(sym_e_error_in_type_def);
                pt2.free;
                pt2.free;
+               pt2 := nil;
              end
              end
            else
            else
              begin
              begin
@@ -1393,6 +1396,7 @@ implementation
                  Message(sym_e_error_in_type_def);
                  Message(sym_e_error_in_type_def);
              end;
              end;
            pt1.free;
            pt1.free;
+           pt1 := nil;
            block_type:=old_block_type;
            block_type:=old_block_type;
         end;
         end;
 
 
@@ -1644,6 +1648,7 @@ implementation
                            Message(sym_e_error_in_type_def)
                            Message(sym_e_error_in_type_def)
                        end;
                        end;
                      pt.free;
                      pt.free;
+                     pt := nil;
                    end;
                    end;
 
 
                   { if we are not at the first dimension, add the new arrray
                   { if we are not at the first dimension, add the new arrray
@@ -1910,6 +1915,7 @@ implementation
                        else
                        else
                         Message(parser_e_illegal_expression);
                         Message(parser_e_illegal_expression);
                        p.free;
                        p.free;
+                       p := nil;
                        { please leave that a note, allows type save }
                        { please leave that a note, allows type save }
                        { declarations in the win32 units ! }
                        { declarations in the win32 units ! }
                        if (not first) and (v<=l) and (not enumdupmsg) then
                        if (not first) and (v<=l) and (not enumdupmsg) then

+ 2 - 0
compiler/rasm.pas

@@ -97,7 +97,9 @@ unit rasm;
     destructor tasmreader.destroy;
     destructor tasmreader.destroy;
       begin
       begin
         locallabels.Free;
         locallabels.Free;
+        locallabels := nil;
         iasmops.Free;
         iasmops.Free;
+        iasmops := nil;
         inherited destroy;
         inherited destroy;
       end;
       end;
 
 

+ 2 - 1
compiler/rautils.pas

@@ -520,6 +520,7 @@ Begin
   expr:=TExprParse.create;
   expr:=TExprParse.create;
   CalculateExpression:=expr.Evaluate(expression);
   CalculateExpression:=expr.Evaluate(expression);
   expr.Free;
   expr.Free;
+  expr := nil;
 end;
 end;
 
 
 
 
@@ -1271,7 +1272,7 @@ var
   i : longint;
   i : longint;
 Begin
 Begin
   for i:=1 to max_operands do
   for i:=1 to max_operands do
-   Operands[i].free;
+   FreeAndNil(Operands[i]);
 end;
 end;
 
 
 
 

+ 7 - 1
compiler/rgobj.pas

@@ -498,11 +498,15 @@ unit rgobj;
         live_registers.done;
         live_registers.done;
 
 
         move_garbage.free;
         move_garbage.free;
+        move_garbage := nil;
         worklist_moves.free;
         worklist_moves.free;
+        worklist_moves := nil;
 
 
         dispose_reginfo;
         dispose_reginfo;
         extended_backwards.free;
         extended_backwards.free;
+        extended_backwards := nil;
         backwards_was_first.free;
         backwards_was_first.free;
+        backwards_was_first := nil;
       end;
       end;
 
 
 
 
@@ -683,6 +687,7 @@ unit rgobj;
             end;
             end;
         until endspill;
         until endspill;
         ibitmap.free;
         ibitmap.free;
+        ibitmap := nil;
 
 
         translate_registers(list);
         translate_registers(list);
 
 
@@ -695,7 +700,7 @@ unit rgobj;
         }
         }
 
 
         for i:=0 to High(spillinfo) do
         for i:=0 to High(spillinfo) do
-          spillinfo[i].interferences.Free;
+          FreeAndNil(spillinfo[i].interferences);
         spillinfo:=nil;
         spillinfo:=nil;
       end;
       end;
 
 
@@ -2552,6 +2557,7 @@ unit rgobj;
             end;
             end;
         list.insertlistafter(headertai,templist);
         list.insertlistafter(headertai,templist);
         templist.free;
         templist.free;
+        templist := nil;
         { Walk through all instructions, we can start with the headertai,
         { Walk through all instructions, we can start with the headertai,
           because before the header tai is only symbols }
           because before the header tai is only symbols }
         p:=headertai;
         p:=headertai;

+ 24 - 2
compiler/scanner.pas

@@ -1098,11 +1098,17 @@ type
   class destructor texprvalue.destroydefs;
   class destructor texprvalue.destroydefs;
     begin
     begin
       setdef.free;
       setdef.free;
+      setdef := nil;
       sintdef.free;
       sintdef.free;
+      sintdef := nil;
       uintdef.free;
       uintdef.free;
+      uintdef := nil;
       booldef.free;
       booldef.free;
+      booldef := nil;
       strdef.free;
       strdef.free;
+      strdef := nil;
       realdef.free;
       realdef.free;
+      realdef := nil;
     end;
     end;
 
 
   constructor texprvalue.create_const(c: tconstsym);
   constructor texprvalue.create_const(c: tconstsym);
@@ -2264,6 +2270,7 @@ type
                     else
                     else
                       result:=texprvalue.create_int(0);
                       result:=texprvalue.create_int(0);
                     exprvalue.free;
                     exprvalue.free;
+                    exprvalue := nil;
                     if current_scanner.preproc_token =_RKLAMMER then
                     if current_scanner.preproc_token =_RKLAMMER then
                       preproc_consume(_RKLAMMER)
                       preproc_consume(_RKLAMMER)
                     else
                     else
@@ -2279,6 +2286,7 @@ type
                     else
                     else
                       result:=texprvalue.create_bool(false); {Just to have something}
                       result:=texprvalue.create_bool(false); {Just to have something}
                     exprvalue.free;
                     exprvalue.free;
+                    exprvalue := nil;
                   end
                   end
                 else
                 else
                 if (current_scanner.preproc_pattern='TRUE') then
                 if (current_scanner.preproc_pattern='TRUE') then
@@ -2455,6 +2463,7 @@ type
                else
                else
                  Message(scan_e_error_in_preproc_expr);
                  Message(scan_e_error_in_preproc_expr);
                exprvalue.free;
                exprvalue.free;
+               exprvalue := nil;
              end
              end
            else
            else
              Message(scan_e_error_in_preproc_expr);
              Message(scan_e_error_in_preproc_expr);
@@ -2508,7 +2517,9 @@ type
                      result:=texprvalue.create_bool(false); {Just to have something}
                      result:=texprvalue.create_bool(false); {Just to have something}
                  end;
                  end;
                hs1.free;
                hs1.free;
+               hs1 := nil;
                hs2.free;
                hs2.free;
+               hs2 := nil;
              end
              end
            else
            else
              break;
              break;
@@ -2538,6 +2549,7 @@ type
           end;
           end;
         valuedescr:=hs.asStr;
         valuedescr:=hs.asStr;
         hs.free;
         hs.free;
+        hs := nil;
       end;
       end;
 
 
     procedure dir_if;
     procedure dir_if;
@@ -2720,6 +2732,7 @@ type
              else
              else
                Message(scan_e_preproc_syntax_error);
                Message(scan_e_preproc_syntax_error);
              exprvalue.free;
              exprvalue.free;
+             exprvalue := nil;
           end
           end
         else
         else
           Message(scan_e_preproc_syntax_error);
           Message(scan_e_preproc_syntax_error);
@@ -3094,8 +3107,12 @@ type
         if not inputfile.closed then
         if not inputfile.closed then
           closeinputfile;
           closeinputfile;
         if inputfile.is_macro then
         if inputfile.is_macro then
-          inputfile.free;
+          begin
+            inputfile.free;
+            inputfile := nil;
+          end;
         ignoredirectives.free;
         ignoredirectives.free;
+        ignoredirectives := nil;
       end;
       end;
 
 
 
 
@@ -3227,7 +3244,7 @@ type
            inputfile.close;
            inputfile.close;
            inputfile:=inputfile.next;
            inputfile:=inputfile.next;
            if assigned(to_dispose) then
            if assigned(to_dispose) then
-             to_dispose.free;
+             to_dispose.free; // no nil needed
            restoreinputfile;
            restoreinputfile;
          end;
          end;
       end;
       end;
@@ -3923,6 +3940,7 @@ type
                         if assigned(pmsg) then
                         if assigned(pmsg) then
                           dispose(pmsg);
                           dispose(pmsg);
                         msgset.free;
                         msgset.free;
+                        msgset := nil;
                       end;
                       end;
                     ST_LINE:
                     ST_LINE:
                       begin
                       begin
@@ -6872,6 +6890,7 @@ exit_label:
             result:=false;
             result:=false;
           end;
           end;
         hs.free;
         hs.free;
+        hs := nil;
       end;
       end;
 
 
 
 
@@ -6891,6 +6910,7 @@ exit_label:
             result:=false;
             result:=false;
           end;
           end;
         hs.free;
         hs.free;
+        hs := nil;
       end;
       end;
 
 
 
 
@@ -6998,7 +7018,9 @@ exit_label:
     procedure DoneScanner;
     procedure DoneScanner;
       begin
       begin
         turbo_scannerdirectives.Free;
         turbo_scannerdirectives.Free;
+        turbo_scannerdirectives := nil;
         mac_scannerdirectives.Free;
         mac_scannerdirectives.Free;
+        mac_scannerdirectives := nil;
         DoneWideString(patternw);
         DoneWideString(patternw);
       end;
       end;
 
 

+ 1 - 0
compiler/switches.pas

@@ -463,6 +463,7 @@ procedure flushpendingswitchesstate;
         pendingstate.nextmessagerecord:=nil;
         pendingstate.nextmessagerecord:=nil;
       end;
       end;
     msgset.free;
     msgset.free;
+    msgset := nil;
     { process pending calling convention changes (calling x) }
     { process pending calling convention changes (calling x) }
     if pendingstate.nextcallingstr<>'' then
     if pendingstate.nextcallingstr<>'' then
       begin
       begin

+ 3 - 0
compiler/symbase.pas

@@ -270,9 +270,11 @@ implementation
           exit;
           exit;
         Clear;
         Clear;
         DefList.Free;
         DefList.Free;
+        DefList := nil;
         { SymList can already be disposed or set to nil for withsymtable, }
         { SymList can already be disposed or set to nil for withsymtable, }
         { but in that case Free does nothing                              }
         { but in that case Free does nothing                              }
         SymList.Free;
         SymList.Free;
+        SymList := nil;
         stringdispose(name);
         stringdispose(name);
         stringdispose(realname);
         stringdispose(realname);
       end;
       end;
@@ -522,5 +524,6 @@ initialization
 
 
 finalization
 finalization
   memrealnames.free;
   memrealnames.free;
+  memrealnames := nil;
 {$endif MEMDEBUG}
 {$endif MEMDEBUG}
 end.
 end.

+ 2 - 1
compiler/symcreat.pas

@@ -180,7 +180,7 @@ implementation
     begin
     begin
       if sstate.valid then
       if sstate.valid then
         begin
         begin
-          sstate.new_scanner.free;
+          sstate.new_scanner.free; // no nil needed
           set_current_scanner(sstate.old_scanner);
           set_current_scanner(sstate.old_scanner);
           current_filepos:=sstate.old_filepos;
           current_filepos:=sstate.old_filepos;
           token:=sstate.old_token;
           token:=sstate.old_token;
@@ -724,6 +724,7 @@ implementation
             str:=str+'__fpc_ord2enum.put(JLInteger.valueOf('+tostr(enumsym.value)+'),'+enumname+');';
             str:=str+'__fpc_ord2enum.put(JLInteger.valueOf('+tostr(enumsym.value)+'),'+enumname+');';
         end;
         end;
       orderedenums.free;
       orderedenums.free;
+      orderedenums := nil;
       str:=str+' end;';
       str:=str+' end;';
       str_parse_method_impl(str,pd,true);
       str_parse_method_impl(str,pd,true);
     end;
     end;

Some files were not shown because too many files changed in this diff