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

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

问题描述

删除分配的内存时出现访问冲突读取位置"异常,如下所示.

I'm getting "Access violation reading location" exception when deleting the allocated memory as follow.

我有一个针对 Visual Studio 2010(工具集:v100)C++ 编译器编译的本机 dll.我有一个托管的 dll 包装器,它是针对工具集 v90 编译的,因为我想针对 .net 2.0.

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.

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

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.

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

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.

是不是因为受保护的本机 dll 地址空间导致我收到异常?如果我使用 v90 工具集编译本机 dll,包装器似乎会毫无例外地删除数组,这很奇怪.

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.
}

谢谢,穆达西尔

推荐答案

您在一个 C++ 运行时 (v100) 中分配并在另一个 (v90) 中释放;那只是自找麻烦.

You're allocating in one C++ runtime (v100) and freeing in another (v90); that's just asking for trouble.

您应该在调用 new[] 的同一个 DLL 中调用 delete[](或者,至少从使用相同运行时库的另一个 DLL 中调用).这很复杂吗?是的;这就是 COM(然后是 .NET)被发明的原因.

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天全站免登陆