ATL C++ memory leak with safearray of ccomobjects - c++

I find myself in need of help. Now, I'm not all that unfamiliar with C++, but combining it with ATL provides a whole new level of confusion. Anyways, my problem: I (finally) managed to return an array of objects in my COM method to C# caller. But upon 'testing' (running said function a number of times repeatedly) I recognized a small memory leak.
IDL excerpt:
...
interface IDISControl : IDispatch{
...
[id(12)] HRESULT GetNets([out,retval] VARIANT* nets);
};
Header excerpt:
...
STDMETHOD(GetNets)(VARIANT* nets);
...
Code:
STDMETHODIMP CDISControl::GetNets(VARIANT* nets)
{
SNet *netz;
int32_t num;
int result, i;
result = DIS_GetNetNum(securityHandle, &num);
netz = new SNet[num];
result = DIS_GetNet(securityHandle, netz, num); //getting some data
CComSafeArray<IDispatch*> netArray;
CComObject<CDISNet> *net;
CComVariant *var;
netArray.Create(num, 0);
for (i = 0;i<num;i++){
CComObject<CDISNet>::CreateInstance(&net);
if (net == NULL)
return S_FALSE;
net->AddRef();
net->Convert(netz[i]);
netArray[i] = net;
net->Release();
net = NULL;
}
CComVariant val(netArray.Detach());
val.Detach(nets);
delete [] netz;
netArray.Destroy();
return S_OK;
}
I instantiate CDISNet objects and put some data in them (Convert()). I put them in my safearray and release. As I understand it, the responsibility for destroying them is transferred to safearray. Afterwards, I box the array in a VARIANT so I can fill my [out, retval] parameter. Since it's an out parameter, the responsibility for destruction should be transferred to caller (in my case C#, i.e. its GarbageCollector). I dispose of my dynamic array 'netz' and I destroy safearray wrapper.
So what am I missing? What is left allocated? (This project is really making me appreciate all the comforts of .net).
Help. Please.
EDIT: Further debugging revealed to me that the problem is certainely in my CComObject objects. They aren't being deallocated. If I delete net; in each iteration the array also looses data. I'm unsure as how to rectify that...
EDIT2:
Ok, I poked around this code for a bit, and the leak seems to go away when I comment out variant boxing. The problem is that I borrowed this piece of code from Visual Studio sample on safearrays. So, does anyone have any idea what's up with:
CComVariant val(netArray.Detach());
val.Detach(nets);
...and what to do about it?

Most, if not all, of ATL's wrappers follow COM conventions -- they copy/addref incoming data, as their destructor will destroy/release.
So when you pass your detached SAFEARRAY to CComVariant's constructor, it will make a copy of the SAFEARRAY, which means nobody releases the result from CComSafeArray::Detach.
In cases like this, I always found it easier to forego the wrapper for the return value entirely;
nets->vt = VT_ARRAY | VT_DISPATCH;
nets->parray = netArray.Detach();
The alternative would be to pass your CComSafeArray directly to CComVariant's constructor, without calling Detach, but that would cost you an extra copy. I'd prefer the raw access presented above, as it is most straightforward and cheapest.
As to your first edit, what you're doing with AddRef/Release is fine, if somewhat unnecessary. CComObject::CreateInstance returns an object with reference count 0, so the AddRef will bring it to 1, and then assigning it to the CComSafeArray will bump it to 2, and the following Release back down to 1.
Unless the Convert method does anything with the object's reference count (e.g. QueryInterface itself or pass itself to another COM method), you could skip the AddRef/Release pair, and let Convert execute with refcount == 0. Then adding it to the array would increase it, and it would stay alive until released.

Related

Memory leak on CreateErrorInfo when analyze from debugdiag?

I am analyzing a memory dump created by debugdiag. It shows CreateErrorinfo method call which leads to memory leak like below,
I am using proper map files for mydll and myanotherdll both. What is the meaning of CreateErrorInfo ? how it's leading to memory leak?
Function Source Destination
mfc90u!operator new+33
mfc90u!CPlex::Create+1f mfc90u!operator new
kernel32!TlsSetValueStub
kernel32!TlsSetValueStub
MYANOTHERDLL!CreateErrorInfo+188e2
MYDLL!MyClas::OnTimer+a3 ......\myfile.cpp # 4639
MYDLL!CMainFrame::OnTimer+71 ......\mainfrm.cpp # 1246
mfc90u!CWnd::OnWndMsg+407
mfc90u!AfxCallWndProc+a3
user32!MDIClientWndProcW
mfc90u!__sse2_available_init+657b
mfc90u!CWnd::WindowProc+24
mfc90u!AfxCallWndProc+a3
mfc90u!AfxWndProc+37 mfc90u!AfxCallWndProc
mfc90u!AfxWndProcBase+56 mfc90u!AfxWndProc
mfc90u!AfxWndProcBase
Is this related to not releasing an interface? Interface from CreatorErroInfo must be released by client:
ICreateErrorInfo* pErrorInfo = nullptr;
HRESULT hr = ::CreateErrorInfo(&pErrorInfo);
if (pErrorInfo)
{
pErrorInfo->Release();
}
Even better to use ATL's smart pointers:
CComPtr<ICreateErrorInfo> ptrErrorInfo;
HRESULT hr = ::CreateErrorInfo(&ptrErrorInfo);
if (ptrErrorInfo)
{
//no release necessary
}
CreateErrorInfo creates an instance of a generic error object.
This function returns a pointer to a generic error object, which you can use with QueryInterface on ICreateErrorInfo to set its contents. I believe you should check the state of ICreateErrorInfo pointer for more details in your code.

When to use SafeArrayAccessData to lock a SAFEARRAY

I'm having a question about when it is necessary to use SafeArrayAccessData to lock a SAFEARRAY, which is passed by managed code.
Here is our code. The VARIANT is passed by managed code, with a string array. During code review, somebody suggest to use SafeArrayAccessData/SafeArrayUnAccessData. But he is not sure about why and what's the benefit. Can you share some of your experiences? Thanks!
STDMETHODIMP Base::Method1(VARIANT values, VARIANT_BOOL result)
{
CComSafeArray<BSTR> ids;
ids.Attach(values.parray);
unsigned int size = ids.GetCount();
for(unsigned int i = 0; i < size; ++i)
{
// use ids[i] here
}
// ...
}
Well, always :) You need it to get a reference to the array content.
But you use a friendly C++ wrapper class. The CComSafeArray<> template already does this for you so you should not help. It uses SafeArrayLock() in the Attach() method, that also returns a pointer to the array content like SafeArrayAccessData() does. And automatically unlocks with its destructor, it runs at the end of your method. Locking otherwise ensures that the array access is thread-safe and cannot be deleted while you are accessing it. There is little danger of that in your existing code, but this squarely fits the better-safe-than-sorry principles of Automation.

Casting COM Interfaces

I came across a problem in my code today where an access violation was being caused, AFAICT, by casting a COM object of mine to an IUnknown**. The function it was passed into executed without a problem but when calling one of my object's functions it would execute some random function and corrupt the stack then die.
Indicative code (just ignore why it's done this way - I know it's bad and I know how to fix it but this is a question of why problems like this may occur):
void MyClass2::func(IMyInterface* pMyObj)
{
CComPtr<IMyInterface2> pMyObj2;
HRESULT hRes = pMyObj->GetInternalObject((IUnknown**)&pMyObj2);
if (SUCCEEDED(hRes))
pMyObj2->Function(); // corrupt stack
}
void MyClass::GetInternalObject(IUnknown** lpUnknown)
{
pInternalObject->QueryInterface(IID_IMyInterface2, (void**)lpUnknown);
}
I have always been a bit suspicious of using C/C++ casts on COM objects but I've never encountered (possibly through undefined behaviour) any problems until now.
I had a quick look and from what I can tell casting to IUnknown is technically valid so long as there is no multiple interitance in the inheritance chain, however it is not considered best practice - I should really pass an IUnknown to MyClass::GetInternalObject(IUnknown** lpUnknown) and then query the return value for the interface I want.
My question is, are there rules as to when C/C++ casts can be used on COM objects, and aside from multiple inheritance and the adjustor thunks they bring, how can casting COM objects result in surprises like access violations? Please be detailed.
Edit: They're all good examples of how it should be done properly but what I was hoping for was a technical explanation of why you shouldn't cast COM objects (assuming one exists) e.g. casting will return pMyObj2-4 in situation x but QueryInterface will return pMyObj2-8 because of y...or is casting COM objects simply a matter of bad practice/style?
TIA
I'd just use CComPtr and CComQIPtr to manage COM interfaces, instead of writing code with C-style casts that to me seem inappropriate in the context of COM:
void MyClass2::Func(IMyInterface* pMyObj)
{
// Assuming:
// HRESULT IMyInterface::GetInternalObject( /* [out] */ IUnknown** )
CComPtr<IUnknown> spUnk;
HRESULT hr = pMyObj->GetInternalObject(&spUnk);
if (SUCCEEDED(hr))
{
// Get IMyInterface2 via proper QueryInterface() call.
CComQIPtr<IMyInterface2> spMyObj2( spUnk );
if ( spMyObj2 )
{
// QueryInterface() succeeded
spMyObj2->Function();
}
}
}
Moreover, I'm not a COM expert, but I see with suspicion your code:
void MyClass::GetInternalObject(IUnknown** lpUnknown)
{
pInternalObject->QueryInterface(IID_IMyInterface2, (void**)lpUnknown);
}
If you are QueryInterface()'ing IID_MyInterface2, you should store that in an IMyInterface2*, not in an IUnknown*.
If your method returns an IUnknown*, then I'd QueryInterface() an IID_IUnknown:
// NOTE on naming convention: your "lpUnknown" is confusing.
// Since it's a double indirection pointer, you may want to use "ppUnknown".
//
void MyClass::GetInternalObject(IUnknown** ppUnknown)
{
pInternalObject->QueryInterface(IID_IUnknown, (void**)ppUnknown);
}
or better use IID_PPV_ARGS macro:
void MyClass::GetInternalObject(IUnknown** ppUnknown)
{
IUnknown* pUnk = NULL;
HRESULT hr = pInternalObject->QueryInterface(IID_PPV_ARGS(&pUnk));
// Check hr...
// Write output parameter
*ppUnknown = pUnk;
}
COM style casts have a specific name: QueryInterface().
I think the issue is that because a cast from IMyInterface* to IUnknown* is OK (in COM everything inherits from IUknown right?) you think that a cast from IMyInterface** to IUnknown** is also OK. But that's not true in C++, and I doubt it's true in COM either.
To me the following looks more logical, apologies if this isn't strictly correct, my COM is very rusty, but hopefully you get the idea.
CComPtr<IUnknown> pMyObj2;
HRESULT hRes = pMyObj->GetInternalObject(&pMyObj2);
if (SUCCEEDED(hRes))
{
CComPtr<IMyInterface> pMyObj3 = (IMyInterface*)pMyObj2;
pMyObj3->Function();
}
I.e. get an IUnknown object first, and then down cast that to your actual type.
I don't see any issues in your code snippets, the stack corruption perhaps has its cause but its somewhere else.
I don't think it is your actual code because GetInternalObject should be of HRESULT type and yours is not, so you lost something during copy/pasting.
To stay safer, just avoid direct QueryInterface calls because together with casting they might misinterpret interfaces. Casting to and from IUnknown* might be inevitable though. If the callee cannot be trusted to return proper interface casted to IUnknown, on the caller side you might prefer to QI once again to make sure you hold the interface of your interest.
Provided that GetInternalObject is a COM interface method on its own, you could have it like this:
void MyClass2::func(IMyInterface* pMyObj)
{
CComPtr<IUnknown> pMyObj2Unknown;
pMyObj->GetInternalObject((IUnknown**)&pMyObj2Unknown);
CComQIPtr<IMyInterface2> pMyObj2 = pMyObj2Unknown; // This is only needed if callee is not trusted to return you a correct pointer
if (pMyObj2)
pMyObj2->Function(); // corrupt stack
}
STDMETHODIMP MyClass::GetInternalObject(IUnknown** lpUnknown) // COM method is typically both HRESULT and __stdcall
{
CComQIPtr<IMyInterface2> pMyInterface2 = pInternalObject;
if(!pMyInterface2)
return E_NOINTERFACE;
*lpUnknown = pMyInterface2.Detach(); // *lpUnknown will have to me IMyInterface2 this way
return S_OK;
}
PS If GetInternalObject was a native method, not COM, you would avoid casting to IUnknown* at all.

c++, msxml and smart pointers

I need parse some XML and wrote some helpers. I am not expert in C++, actually I wrote with c more then seven years ago. So, I would to make sure, is the approach, what i use correct or not :)
1) I implemented some simple helpers, to take care about exceptions.
For example:
CComPtr<IXMLDOMElement> create_element(CComPtr<IXMLDOMDocument> xml_doc, string element_name) {
CComPtr<IXMLDOMElement> element;
HRESULT hr = xml_doc->createElement((BSTR)element_name.c_str(), &element);
if (FAILED(hr))
hr_raise("Failed to create XML element '" + element_name + "'", hr);
return element;
}
and use it like this:
void SomeClass::SomeMethod() {
CComPtr<IXMLDOMElement> element = xmlh::create_element(xml_doc, "test");
//..
// save xml to file
}
is it ok? I mean can i return smart pointer as function result? Is this approach free from leaks?
2) Also i use some smartpointer as Class Members.
Like this:
class XMLCommand {
public:
XMLCommand(std::string str_xml);
~XMLCommand(void);
protected:
CComPtr<IXMLDOMDocument> xml_doc;
}
XMLCommand::XMLCommand(string str_xml) {
xml_doc = xmlh::create_xml_doc();
}
// some methods below uses xml_doc
The question is the same, is it correct and free from leaks?
Thanks.
That will work fine. When returning a smart pointer from function, the result is stored before the temporaries are destructed, so as long as you store it in a CComPtr<IXMLDOMElement> when you call create_element you will get the desired results (e.g., CComPtr<IXMLDOMElement> resElem = create_element(...);. Optimized C++ will very likely even not bother with temporaries and such and just use resElem instead of element inside your create_element() method, speeding up the process (google Return Value Optimization for details).
The latter case is pretty much textbook smart-pointer usage. I can't think of a case that will fail. One danger when using smart pointers in general though is to be aware of and/or avoid circular dependencies, which can cause smart pointers to never delete their contained object.

Pointer object in C++

I have a very simple class that looks as follows:
class CHeader
{
public:
CHeader();
~CHeader();
void SetCommand( const unsigned char cmd );
void SetFlag( const unsigned char flag );
public:
unsigned char iHeader[32];
};
void CHeader::SetCommand( const unsigned char cmd )
{
iHeader[0] = cmd;
}
void CHeader::SetFlag( const unsigned char flag )
{
iHeader[1] = flag;
}
Then, I have a method which takes a pointer to CHeader as input and looks
as follows:
void updateHeader(CHeader *Hdr)
{
unsigned char cmd = 'A';
unsigned char flag = 'B';
Hdr->SetCommand(cmd);
Hdr->SetFlag(flag);
...
}
Basically, this method simply sets some array values to a certain value.
Afterwards, I create then a pointer to an object of class CHeader and pass it to
the updateHeader function:
CHeader* hdr = new CHeader();
updateHeader(hdr);
In doing this, the program crashes as soon as it executes the Hdr->SetCommand(cmd)
line. Anyone sees the problem, any input would be really appreciated
When you run into a crash, act like a crime investigator: investigate the crime scene.
what is the information you get from your environment (access violation? any debug messages? what does the memory at *Hdr look like? ...)
Is the passed-in Hdr pointer valid?
Then use logical deduction, e.g.:
the dereferencing of Hdr causes an access violation
=> passed in Hdr points to invalid memory
=> either memory wasn't valid to start with (wrong pointer passed in), or memory was invalidated (object was deleted before passing in the pointer, or someone painted over the memory)
...
It's probably SEGFAULTing. Check the pointers.
After
your adding some source code
your comment that the thing runs on another machine
the fact that you use the term 'flag' and 'cmd' and some very small datatypes
making me assume the target machine is quite limited in capacity, I suggest testing the result of the new CHeader for validity: if the system runs out of resources, the resulting pointer will not refer to valid memory.
There is nothing wrong with the code you've provided.
Are you sure the pointer you've created is the same same address once you enter the 'updateHeader' function? Just to be sure, after new() note the address, fill the memory, sizeof(CHeader), with something you know is unique like 0XDEAD, then trace into the updateHeader function, making sure everything is equal.
Other than that, I wonder if it is an alignment issues. I know you're using 8 bit values, but try changing your array to unsigned ints or longs and see if you get the same issue. What architecture are you running this on?
Your code looks fine. The only potential issue I can see is that you have declared a CHeader constructor and destructor in your class, but do not show the implementation of either. I guess you have just omitted to show these, else the linker should have complained (if I duplicate this project in VC++6 it comes up with an 'unresolved external' error for the constructor. It should also have shown the same error for the destructor if you had a... delete hdr; ...statement in your code).
But it is actually not necessary to have an implementation for every method declared in a class unless the methods are actually going to get called (any unimplemented methods are simply ignored by the compiler/linker if never called). Of course, in the case of an object one of the constructor(s) has to be called when the object is instantiated - which is the reason the compiler will create a default constructor for you if you omit to add any constructors to your class. But it will be a serious error for your compiler to compile/link the above code without the implementation of your declared constructor, so I will really be surprised if this is the reason for your problem.
But the symptoms you describe definitely sounds like the 'hdr' pointer you are passing to the updateHeader function is invalid. The reason being that the 1st time you are dereferencing this pointer after the updateHeader function call is in the... Hdr->SetCommand(cmd); ...call (which you say crashes).
I can only think of 2 possible scenarios for this invalid pointer:
a.) You have some problem with your heap and the allocation of memory with the 'new' operator failed on creation of the 'hdr' object. Maybe you have insufficient heap space. On some embedded environments you may also need to provide 'custom' versions of the 'new' and 'delete' operator. The easiest way to check this (and you should always do) is to check the validity of the pointer after the allocation:
CHeader* hdr = new CHeader();
if(hdr) {
updateHeader(hdr);
}
else
//handle or throw exception...
The normal behaviour when 'new' fails should actually be to throw an exception - so the following code will cater for that as well:
try{
CHeader* hdr = new CHeader();
} catch(...) {
//handle or throw specific exception i.e. AfxThrowMemoryException() for MFC
}
if(hdr) {
updateHeader(hdr);
}
else
//handle or throw exception...
}
b.) You are using some older (possibly 16 bit and/or embedded) environment, where you may need to use a FAR pointer (which includes the SEGMENT address) for objects created on the heap.
I suspect that you will need to provide more details of your environment plus compiler to get any useful feedback on this problem.