头大的内存泄漏
function LoadTemplateJsonFromDB(ATemplateID: Integer): TJSONObject;//注意返回对象 var Q: TFDQuery; S: string; RootVal: TJSONValue; RootArr: TJSONArray; begin Result := nil; Q := TFDQuery.Create(nil); try Q.Connection := UniMainModule.FDConnection1; Q.SQL.Text := 'SELECT template_json FROM user001.ops_report_template WHERE id = :tid'; Q.ParamByName('tid').AsInteger := ATemplateID; Q.Open; if Q.IsEmpty then Exit; S := Trim(Q.FieldByName('template_json').AsString); finally Q.Free; end; if S = '' then Exit; //一定要这样处理!!!!!! RootVal := TJSONObject.ParseJSONValue(S); if RootVal = nil then Exit; try if RootVal is TJSONArray then begin RootArr := TJSONArray(RootVal); if RootArr.Count > 0 then Result := TJSONObject(RootArr.Items[0].Clone); // ★ Clone 出来交给外部 end else if RootVal is TJSONObject then Result := TJSONObject(RootVal.Clone); finally RootVal.Free; // ★ 无论如何释放根节点,避免泄漏 TJSONArray/TList end; end;
这个内存泄漏相当难查。是一个非常隐蔽的大坑。
浙公网安备 33010602011771号