删除阵列时访问冲突异常 [英] Access violation exception when deleting an array

查看:215
本文介绍了删除阵列时访问冲突异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下所示,在删除已分配的内存时,我收到访问冲突读取位置异常。



我有一个针对Visual Studio 2010编译的本地dll(工具集: v100)C ++编译器。我有一个管理的dll包装器,它是根据工具集v90编译的,因为我想要定位到.net 2.0。



托管包装器将引用传递给指针(double *& myArray)到本地dll函数调用之一,它在内部创建一个动态数组并初始化数据。



但是,当托管包装器尝试通过调用delete [] myArray来释放包装器时,它会抛出异常。它似乎工作正常如果我要求本机dll释放它。



是因为受保护的本机dll地址空间,我得到异常?如果我用v90工具集编译本机dll,包装似乎删除数组没有任何异常是奇怪的。



什么是最好的方法删除这样的用例?

  // Managed.cpp 
void InitializeData()
{
double * myArray;
myNativeObj-> InitializeArray(myArray);
delete [] myArray; //< - Exception here
}

//UnManaged.cpp
void InitializeArray(double *& myArray)
{
myArray = new double [get_length()];
//将数据初始化到我的数组。
}

谢谢,
Mudassir


<你分配在一个C ++运行时(v100)和释放在另一个(v90);。



您应该在同一个DLL中调用 delete [] c $ c> new [] (或者,至少从使用相同运行时库的另一个DLL)。这是复杂和凌乱?是;这就是为什么COM(然后.NET)被发明了。


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

解决方案

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.

这篇关于删除阵列时访问冲突异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆