I using crtdbg to detect leak position and I got memory leak when calling new
CComPtr<IDBColumnInfo> m_spColumnInfo
CComPtr<CDBColumnInfo> spResult = new CDBColumnInfo(); //Memory leak here
//another logic come here to set data to spResult
//another logic come here to set data to spResult
//another logic come here to set data to spResult
m_spColumnInfo = static_cast<IDBColumnInfo*>(spResult.Detach());
spResult.Release();
Are there any step need to do with spResult?
You have a memory leak, because you are mismanaging the
CDBColumnInfoobject's reference count.When you initialize
spResult, the object's refcount is initialized to 1. When you callspResult.Detach(), the object still has a refcount of 1, asDetach()does not decrement it. When the detached pointer is then assigned tom_spColumnInfo, the object's refcount is incremented to 2. Whenm_spColumnInfois released later on, it decrements the object's recount to 1, and the object is leaked.You should not be detaching
spResultat all. Assign it as-is tom_spColumnInfo, which will increment the refcount to 2, and then letspResultgo out of scope normally, decrementing the refcount to 1, leavingm_spColumnInfowith the only active reference. Whenm_spColumnInfois then released later on, the refcount will be decremented to 0, and the object will be freed.You shouldn't be trying to manage the refcount manually at all. That defeats the whole purpose of using
CComPtr.Also, on a side note, your function has no business calling
CoInitialize()andCoUninitialize()at all! You need to remove those calls from your function (especially since your function does not even callCoUninitialize()in most of the code paths that exit your function). Those calls are not your function's responsibility to make. It is the responsibility of the thread that calls your function to decide how it needs to initialize COM for itself. Those COM functions should be called only once per thread, not per user function.