Access violation exception when deleting an array

别来无恙 提交于 2019-12-23 16:00:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!