When is it appropriate to use CoTaskMemAlloc? Can someone give an example?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Gosh, I had to think for a while for this one — I’ve done a fair amount of small-scale COM programming with ATL and rarely have had to use it.
There is one situation though that comes to mind: Windows Shell extensions. If you are dealing with a set of filesystem objects you might have to deal with PIDLs (pointer to an ID list). These are bizarre little filesystem object abstractions and they need to be explicitly allocated/deallocated using a COM-aware allocator such as
CoTaskMemAlloc. There is also an alternative, theIMallocinterface pointer obtained fromSHGetMalloc(deprecated) orCoGetMalloc— it’s just an abstraction layer to use, so that your code isn’t tied to a specific memory allocator and can use any appropriate one.The point of using
CoTaskMemAllocorIMallocrather thanmalloc()is that the memory allocation/deallocation needs to be something that is ‘COM-aware’ so that its allocation and deallocation are performed consistently at run-time, even if the allocation and deallocation are done by completely unrelated code (e.g. Windows allocates memory, transfers it to your C++ code which later deallocates, or your C++ code allocates, transfers it to someone else’s VB code which later deallocates). Neithermalloc()norneware capable of interoperating with the system’s run-time heap so you can’t use them to allocate memory to transfer to other COM objects, or to receive memory from other COM objects and deallocate.