Case of Memory Leaks in OPC

In one of the phase of my project, I came across the requirement to create the server application that perform interface from OPC data to existing MS SQL data.

The server component is developed using Visual Basic 6, as for the component that is responsible to connect to OPC server(s) is created using Visual C++ and DCOM framework.

Each of the component is already tested separately and it’s time to combined it into one of the solutions, i.e. to provide or refresh the OPC data list at the interval of 30 seconds.

After performing the setups, I make it run and I intend to perform some routine perfomance check on the next day. To my astonishment, the memory usage of previous day of about 6 MB now grows to an astronomical size of 70 MB !

So I decided to perform detailed check of what’s the causes of growing size of the memory. Using sequences of documented heap memory checks of :

!heap -s

!heap -stat -h {heap handle with growing memory}

I realize that the cause of memory grow is the leaks of many blocks of 128 bytes :

0:010> !heap -stat -h 00140000
heap @ 00140000
group-by: TOTSIZE max-display: 20
size #blocks total ( %) (percent of total busy bytes)
128 942 – ab450 (54.59)

Checks to the user mode stack after activating :

gflags /i myserver.exe +ust

And then using :

!heap -p -a {UserPtr}

Reveals that the source of memory grow is the COM allocation after the call of :

hr = pItemMgt->AddItems(nSize, ItemArray, &pAddResult, &pErrors);

This is weird because I already perform :

CoTaskMemFree(pAddResult);

After each OPC get data item call.

After spending some hours of heap checking, it turns out that the source of leaked memory is in the pBlob pointer of OPCITEMRESULT structure, and this has to be freed one-by-one (when there are more than one results to be returned) as follows :

for (nI=0;nI<nSize;nI++)
CoTaskMemFree((LPVOID)pAddResult[nI].pBlob);

After applying this patch to existing module, I am ready to move to the next phase of the project 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: