问题
I'm getting "Access violation reading location" exception when deleting the allocated memory as follow.
I have a native dll compiled against Visual Studio 2010(toolset: v100) C++ compiler.I have a managed dll wrapper for it which is compiled against toolset v90 as I want to target .net 2.0.
The managed wrapper passes the reference to pointer (double *&myArray) to one of the native dll function call, which internally creates a dynamic array and initializes the data.
However, when managed wrapper tries to release the wrapper by calling delete [] myArray, it throws the exception. It seems working fine If I ask native dll to free it.
Is it because of protected native dll address space that I'm getting the exception ? If I compile native dll with v90 toolset, the wrapper seems to delete the array without any exception which is weird.
What is the best way to delete the memory in such a use case ?
//Managed.cpp
void InitializeData()
{
double *myArray;
myNativeObj->InitializeArray(myArray);
delete[] myArray; // <-- Exception here
}
//UnManaged.cpp
void InitializeArray(double *& myArray)
{
myArray = new double[get_length()];
//Initialize data to my array.
}
Thanks, Mudassir
回答1:
You're allocating in one C++ runtime (v100) and freeing in another (v90); that's just asking for trouble.
You should call delete[]
in the same DLL from which you called new[]
(or, at least from another DLL which uses the same runtime library). Is this complicated and messy? Yes; that's why COM (and then .NET) was invented.
来源:https://stackoverflow.com/questions/15286300/access-violation-exception-when-deleting-an-array