3

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

4
  • 1
    What is the data type of myNativeObj? Are you sure that the intended function is being called. Commented Mar 8, 2013 at 3:42
  • Did you initialized myNativeObj before call myNativeObj->InitializeArray(myArray); Commented Mar 8, 2013 at 4:07
  • 1
    Need an SSCCE, the code looks fine as-is. Commented Mar 8, 2013 at 4:13
  • 1
    can you post what exception are throw, with all runtime error messages? Commented Mar 8, 2013 at 4:16

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Nailed it, apparently I was paying too much attention to the code and not enough to the surrounding text to notice this rather important detail >_>. That said, that's why they invented COM – .NET just got to reap the benefits of prior experience.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.