views:

72

answers:

1

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?

A: 

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:

IMyInterface *l;
SafeArrayGetElement(array,&i, &l);

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.

DavidK
thanks, bits i'd read said that it was the responsibility of the user to allocate the memory for the element to be copied into, but that seems to work a treat.
The documentation is right, if maybe a bit misleading - since the array contains pointers, which are only four bytes, it's enough to pass the address of the pointer variable on the stack. If the array contained bigger objects you'd have to allocate the amount of memory needed somehow.
DavidK