AccessViolationException reading memory allocated in C++ application from C++/CLI DLL
Asked Answered
M

3

11

I have a C++ client to a C++/CLI DLL, which initializes a series of C# dlls.

This used to work. The code that is failing has not changed. The code that has changed is not called before the exception is thrown. My compile environment has changed, but recompiling on a machine with an environment similar to my old one still failed. (EDIT: as we see in the answer this is not entirely true, I was only recompiling the library in the old environment, not the library and client together. The client projects had been upgraded and couldn't easily go back.)

Someone besides me recompiled the library, and we started getting memory management issues. The pointer passed in as a String must not be in the bottom 64K of the process's address space. I recompiled it, and all worked well with no code changes. (Alarm #1) Recently it was recompiled, and memory management issues with strings re-appeared, and this time they're not going away. The new error is Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

I'm pretty sure the problem is not located where I see the exception, the code didn't change between the successful and failing builds, but we should review that to be complete. Ignore the names of things, I don't have much control over the design of what it's doing with these strings. And sorry for the confusion, but note that _bridge and bridge are different things. Lots of lines of code missing because this question is already too long.

Defined in library:

struct Config
{
    std::string aye;
    std::string bee;
    std::string sea;
};

extern "C" __declspec(dllexport) BridgeBase_I* __stdcall Bridge_GetConfiguredDefaultsImplementationPointer(
    const std::vector<Config> & newConfigs, /**< new configurations to apply **/
    std::string configFolderPath, /**< folder to write config files in **/
    std::string defaultConfigFolderPath, /**< folder to find default config files in **/
    std::string & status /**< output status of config parse **/
    );

In client function:

GatewayWrapper::Config bridge;
std::string configPath("./config");
std::string defaultPath("./config/default");
GatewayWrapper::Config gwtransport;
bridge.aye = "bridged.dll";
bridge.bee = "1.0";
bridge.sea = "";
configs.push_back(bridge);
_bridge = GatewayWrapper::Bridge_GetConfiguredDefaultsImplementationPointer(configs, configPath, defaultPath, status);

Note that call to library that is crashing is in the same scope as the vector declaration, struct declaration, string assignment and vector push-back There are no threading calls in this section of code, but there are other threads running doing other things. There is no pointer math here, there are no heap allocations in the area except perhaps inside the standard library.

I can run the code up to the Bridge_GetConfiguredDefaultsImplementationPointer call in the debugger, and the contents of the configs vector look correct in the debugger.

Back in the library, in the first sub function, where the debugger don't shine, I've broken down the failing statement into several console prints.

System::String^ temp
List<CConfig^>^ configs = gcnew List<CConfig ^>((INT32)newConfigs.size());
for( int i = 0; i< newConfigs.size(); i++)
{
  std::cout << newConfigs[i].aye<< std::flush; // prints
  std::cout << newConfigs[i].aye.c_str() << std::flush; // prints
  temp = gcnew System::String(newConfigs[i].aye.c_str());
  System::Console::WriteLine(temp); // prints
  std::cout << "Testing string creation" << std::endl; // prints
  std::cout << newConfigs[i].bee << std::flush; // crashes here
}

I get the same exception on access of bee if I move the newConfigs[i].bee out above the assignment of temp or comment out the list declaration/assignment.

Just for reference that the std::string in a struct in a vector should have arrived at it's destination ok

Why this exception is not caught by my try/catch

https://mcmap.net/q/211169/-catching-access-violation-exceptions

Generic AccessViolationException related questions

Suggestions in above questions

  • Change to .net 3.5, change target platform - these solutions could have serious issues with a large mult-project solution.
  • HandleProcessCorruptedStateExceptions - does not work in C++, this decoration is for C#, catching this error could be a very bad idea anyway
  • Change legacyCorruptedStateExceptionsPolicy - this is about catching the error, not preventing it
  • Install .NET 4.5.2 - can't, already have 4.6.1. Installing 4.6.2 did not help. Recompiling on a different machine that didn't have 4.5 or 4.6 installed did not help. (Despite this used to compile and run on my machine before installing Visual Studio 2013, which strongly suggests the .NET library is an issue?)
  • VSDebug_DisableManagedReturnValue - I only see this mentioned in relation to a specific crash in the debugger, and the help from Microsoft says that other AccessViolationException issues are likely unrelated. (http://connect.microsoft.com/VisualStudio/feedbackdetail/view/819552/visual-studio-debugger-throws-accessviolationexception)
  • Change Comodo Firewall settings - I don't use this software
  • Change all the code to managed memory - Not an option. The overall design of calling C# from C++ through C++/CLI is resistant to change. I was specifically asked to design it this way to leverage existing C# code from existing C++ code.
  • Make sure memory is allocated - memory should be allocated on the stack in the C++ client. I've attempted to make the vector be not a reference parameter, to force a vector copy into explicitly library controlled memory space, did not help.
  • "Access violations in unmanaged code that bubble up to managed code are always wrapped in an AccessViolationException." - Fact, not a solution.
Mulder answered 2/12, 2016 at 22:12 Comment(10)
Not an answer since I cannot be sure, but I place my bet on a standard library implementation mismatch: the std::string definition your C++ code uses is most probably not the same than the std::string definition your C++/CLI code uses. Make sure you're using /MD in both projects, see here and here for more info.Lenlena
Good thought, but that's not it. Both debug builds are using /MDd, both release builds are using /MD.Mulder
Go ahead an post that second link as an answer. It is related. The first time we ran into this issue someone had started compiling the library in visual studio 2013 while the client was still being compiled in 2010. I had fixated on 2013 being a problem, so when the client started being compiled in 2013 I continued compiling the library in 2010, but it was the mismatch, not the specific version that was the problem. Compile both in 2013 and it works fine.Mulder
If it's simply related but does not solve your current problem then it wouldn't really be an answer (you're saying "the first time" so my understanding is that your current issue isn't fixed yet). Besides, you'll get more views with a bounty on a question with no answers.Lenlena
I think it's fixed until someone decides to recompile one of the two in a newer version of VS.Mulder
Ok, first person to provide documentation on why I'm seeing what I'm seeing gets the bounty. If there's a difference in visual studio version between client and server compiles, we get one or another memory management issue with passing strings. If we use 2010 or 2013 for both sides, all is well.Mulder
Well if it's like that then all's clear. It's just a runtime library mismatch like I said. What you're trying to do is for instance allocating an object with one allocator, then deallocating it with an allocator from a different runtime version - that won't go too well. I'll try to write an answer later on.Lenlena
Not deallocating, just reading. Shouldn't be deallocated until after the library function returns and the original object falls out of scope.Mulder
An extensive discussion about what is happening: siomsystems.com/mixing-visual-studio-versionsMulder
More discussion about low level memory layout: randomascii.wordpress.com/2013/12/01/…Mulder
F
9

but it was the mismatch, not the specific version that was the problem

Yes, that's black letter law in VS. You unfortunately just missed the counter-measures that were built into VS2012 to turn this mistake into a diagnosable linker error. Previously (and in VS2010), the CRT would allocate its own heap with HeapAlloc(). Now (in VS2013), it uses the default process heap, the one returned by the GetProcessHeap().

Which is in itself enough to trigger an AVE when you run your app on Vista or higher, allocating memory from one heap and releasing it from another triggers an AVE at runtime, a debugger break when you debug with the Debug Heap enabled.

This is not where it ends, another significant issue is that the std::string object layout is not the same between the versions. Something you can discover with a little test program:

#include <string>
#include <iostream>

int main()
{
    std::cout << sizeof(std::string) << std::endl;
    return 0;
}
  • VS2010 Debug : 32
  • VS2010 Release : 28
  • VS2013 Debug : 28
  • VS2013 Release : 24

I have a vague memory of Stephen Lavavej mentioning the std::string object size reduction, very much presented as a feature, but I can't find it back. The extra 4 bytes in the Debug build is caused by the iterator debugging feature, it can be disabled with _HAS_ITERATOR_DEBUGGING=0 in the Preprocessor Definitions. Not a feature you'd quickly want to throw away but it makes mixing Debug and Release builds of the EXE and its DLLs quite lethal.

Needless to say, the different object sizes seriously bytes when the Config object is created in a DLL built with one version of the standard C++ library and used in another. Many mishaps, the most basic one is that the code will simply read the Config::bee member from the wrong offset. An AVE is (almost) guaranteed. Lots more misery when code allocates the small flavor of the Config object but writes the large flavor of std::string, that randomly corrupts the heap or the stack frame.

Don't mix.

Fico answered 11/12, 2016 at 19:9 Comment(0)
E
6

I believe 2013 introduced a lot of changes in the internal data formats of STL containers, as part of a push to reduce memory usage and improve perf. I know vector became smaller, and string is basically a glorified vector<char>.

Microsoft acknowledges the incompatibility:

"To enable new optimizations and debugging checks, the Visual Studio implementation of the C++ Standard Library intentionally breaks binary compatibility from one version to the next. Therefore, when the C++ Standard Library is used, object files and static libraries that are compiled by using different versions can't be mixed in one binary (EXE or DLL), and C++ Standard Library objects can't be passed between binaries that are compiled by using different versions."

If you're going to pass std::* objects between executables and/or DLLs, you absolutely must ensure that they are using the same version of the compiler. It would be well-advised to have your client and its DLLs negotiate in some way at startup, comparing any available versions (e.g. compiler version + flags, boost version, directx version, etc.) so that you catch errors like this quickly. Think of it as a cross-module assert.

If you want to confirm that this is the issue, you could pick a few of the data structures you're passing back and forth and check their sizes in the client vs. the DLLs. I suspect your Config class above would register differently in one of the fail cases.

I'd also like to mention that it is probably a bad idea in the first place to use smart containers in DLL calls. Unless you can guarantee that the app and DLL won't try to free or reallocate the internal buffers of the other's containers, you could easily run into heap corruption issues, since the app and DLL each have their own internal C++ heap. I think that behavior is considered undefined at best. Even passing const& arguments could still result in reallocation in rare cases, since const doesn't prevent a compiler from diddling with mutable internals.

Enclave answered 9/12, 2016 at 15:34 Comment(2)
Sorry, If I could have split the bounty I would have.Mulder
Another question where the sizes of different objects was discussed. #14090841Mulder
D
0

You seem to have memory corruption. Microsoft Application Verifier is invaluable in finding corruption. Use it to find your bug:

  1. Install it to your dev machine.
  2. Add your exe to it.
  3. Only select Basics\Heaps.
  4. Press Save. It doesn't matter if you keep application verifier open.
  5. Run your program a few times.
  6. If it crashes, debug it and this time, the crash will point to your problem, not just some random location in your program.

PS: It's a great idea to have Application Verifier enabled at all times for your development project.

Dissimulation answered 5/12, 2016 at 18:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.