Pooling = true memory error + possible fix

Discussion of open issues, suggestions and bugs regarding MyDAC (Data Access Components for MySQL) for Delphi, C++Builder, Lazarus (and FPC)
Post Reply
ajy
Posts: 1
Joined: Thu 05 May 2016 09:52

Pooling = true memory error + possible fix

Post by ajy » Thu 05 May 2016 10:12

Hello,

There is a memory error when TMyConnection.Pooling is set to true. This can be seen when using FastMM4 and enabling full debug mode. The error occurs on application shutdown, the following simple example will trigger this issue:

var
conn: TMyConnection;
query: TMyQuery;
begin
conn:=TMyConnection.Create(nil);
try
conn.Options.Direct:=true;
conn.Pooling:=true;
conn.Server:='...';
conn.Database:='...';
conn.Username:='...';
conn.Password:='...';
conn.Open;
query:=TMyQuery.Create(nil);
try
query.Connection:=conn;
query.SQL.Text:='SELECT 1';
query.Open;
finally
query.Free;
end;
finally
conn.Free;
end;
end;

On shutdown FastMM4 reports:

"FastMM has detected an attempt to call a virtual method on a freed object. An access violation will now be raised in order to abort the current operation."

The offending line is in TMySQLConnection.Disconnect

FMySQLAPI.mysql_close(FMySQL);

called from TCRLocalConnectionPool.InternalFreeConnection

It seems the object pointed to by FMySQLAPI has already been destroyed. After some investigation I found that MySQLAPIDirect.pas unit finalization is being called before CRConnectionPool.pas unit finalization. This means that MyAPIDirect has already been freed and as FMySQLAPI points to this it is no longer valid.

A possible fix is to change the order of the unit finalization by adding MySQLApiDirect to the Uses clause of CRConnectionPool.pas, for example:

uses
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
Classes, SysUtils, SyncObjs,
{$IFDEF VER6P}
Types, Variants,
{$ENDIF}
{ AJY }
MySQLApiDirect, // To ensure correct finalization order to avoid memory issue.
CRTypes, CLRClasses, CRVio, CRAccess, MemUtils, DASQLMonitor;

This works and MySQLApiDirect is no longer freed first. Not an ideal solution maybe but hopefully you can fix it properly.

Thanks,

Adrian

ViktorV
Devart Team
Posts: 3168
Joined: Wed 30 Jul 2014 07:16

Re: Pooling = true memory error + possible fix

Post by ViktorV » Fri 13 May 2016 09:43

Thank you for the information. We have reproduced the issue and investigation is in progress. We will inform you when we have any results.

ViktorV
Devart Team
Posts: 3168
Joined: Wed 30 Jul 2014 07:16

Re: Pooling = true memory error + possible fix

Post by ViktorV » Thu 04 May 2017 12:55

The new build of MyDAC including this fix is already available for download.

Post Reply