I have some code in C# which has a com wrapper. This com wrapper is used in a native c++ application. The c++ code uses a method which returns an array of instances of a class from the c# library. The instances come from a SafeArray like so:
for (long i =min; i<=max;i++) { IMyInterface *l = (IMyInterface *)malloc(sizeof IMyInterface ); SafeArrayGetElement(array,&i, &l); <other code> }
I want to free the memory allocated for the instance l, but if I call
free(l)
then I get a crash.
I have tried
VariantClear ((VARIANT*)l);
and using
SafeArrayDestroy(array)
but am still leaking 4 bytes for each instance in the array.
any ideas how I should go about freeing this memory?
This code looks a bit confused: you’re passing ‘sizeof IMyInterface’ to malloc(), which will be the size in memory of an instance of IMyInterface, not a pointer to it: you might well mean ‘sizeof IMyInterface*’ if you want to allocate memory for a pointer.
However, looking at it, that doesn’t make any sense either: wouldn’t you be better off not doing the malloc() at all? The last argument to SafeArrayGetElement() is a pointer to the memory that will hold the result, so the contents of l (the pointer returned by malloc()) will just be overwritten (which is why free() gives you a crash). In other words, just this should work:
Without knowing exactly what’s in the array, it’s not easy to be sure, but it looks like you’re getting confused by the old C/C++ issue of the difference between pointers and the objects they point to.