title: AccessViolationException reading memory allocated in C++ application from C++/CLI DLL
body: <p>I have a C++ client to a C++/CLI DLL, which initializes a series of C# dlls.</p>
  
  <p>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.)</p>
  
  <p>Someone besides me recompiled the library, and we started getting memory management issues.  <code>The pointer passed in as a String must not be in the bottom 64K of the process's address space.</code>  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 <code>Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.</code>  </p>
  
  <p>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 <code>_bridge</code> and <code>bridge</code> are different things.  Lots of lines of code missing because this question is already too long.</p>
  
  <p>Defined in library:</p>
  
  <pre><code>struct Config
  {
      std::string aye;
      std::string bee;
      std::string sea;
  };
  
  extern "C" __declspec(dllexport) BridgeBase_I* __stdcall Bridge_GetConfiguredDefaultsImplementationPointer(
      const std::vector&lt;Config&gt; &amp; newConfigs, /**&lt; new configurations to apply **/
      std::string configFolderPath, /**&lt; folder to write config files in **/
      std::string defaultConfigFolderPath, /**&lt; folder to find default config files in **/
      std::string &amp; status /**&lt; output status of config parse **/
      );
  </code></pre>
  
  <p>In client function:</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>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.</p>
  
  <p>I can run the code up to the <code>Bridge_GetConfiguredDefaultsImplementationPointer</code> call in the debugger, and the contents of the <code>configs</code> vector look correct in the debugger.</p>
  
  <p>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.</p>
  
  <pre><code>System::String^ temp
  List&lt;CConfig^&gt;^ configs = gcnew List&lt;CConfig ^&gt;((INT32)newConfigs.size());
  for( int i = 0; i&lt; newConfigs.size(); i++)
  {
    std::cout &lt;&lt; newConfigs[i].aye&lt;&lt; std::flush; // prints
    std::cout &lt;&lt; newConfigs[i].aye.c_str() &lt;&lt; std::flush; // prints
    temp = gcnew System::String(newConfigs[i].aye.c_str());
    System::Console::WriteLine(temp); // prints
    std::cout &lt;&lt; "Testing string creation" &lt;&lt; std::endl; // prints
    std::cout &lt;&lt; newConfigs[i].bee &lt;&lt; std::flush; // crashes here
  }
  </code></pre>
  
  <p>I get the same exception on access of <code>bee</code> if I move the <code>newConfigs[i].bee</code> out above the assignment of <code>temp</code> or comment out the list declaration/assignment.</p>
  
  <h2>Just for reference that the std::string in a struct in a vector should have arrived at it's destination ok</h2>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/2275076/is-stdvector-copying-the-objects-with-a-push-back">Is std::vector copying the objects with a push_back?</a></li>
  <li><a href="https://stackoverflow.com/questions/2009996/stdstring-in-struct-copy-assignment-issues">std::string in struct - Copy/assignment issues?</a></li>
  <li><a href="http://www.cplusplus.com/reference/vector/vector/operator=/" rel="nofollow noreferrer">http://www.cplusplus.com/reference/vector/vector/operator=/</a></li>
  <li><a href="https://stackoverflow.com/questions/2302351/assign-one-struct-to-another-in-c">Assign one struct to another in C</a></li>
  </ul>
  
  <h2>Why this exception is not caught by my try/catch</h2>
  
  <p><a href="https://stackoverflow.com/a/918891/2091951">https://stackoverflow.com/a/918891/2091951</a></p>
  
  <h2>Generic AccessViolationException related questions</h2>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/3469368/how-to-handle-accessviolationexception">How to handle AccessViolationException</a></li>
  <li><a href="https://stackoverflow.com/questions/24294543/programs-randomly-getting-system-accessviolationexception">Programs randomly getting System.AccessViolationException</a></li>
  <li><a href="https://connect.microsoft.com/VisualStudio/feedback/details/819552/visual-studio-debugger-throws-accessviolationexception" rel="nofollow noreferrer">https://connect.microsoft.com/VisualStudio/feedback/details/819552/visual-studio-debugger-throws-accessviolationexception</a></li>
  <li><a href="https://stackoverflow.com/questions/5133971/finding-the-cause-of-system-accessviolationexception">finding the cause of System.AccessViolationException</a></li>
  <li><a href="https://msdn.microsoft.com/en-us/library/ms164911.aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/ms164911.aspx</a></li>
  <li><a href="https://stackoverflow.com/questions/457577/catching-access-violation-exceptions">Catching access violation exceptions?</a></li>
  <li><a href="https://stackoverflow.com/questions/27386936/accessviolationexception-when-using-c-dll-from-c-sharp">AccessViolationException when using C++ DLL from C#</a></li>
  </ul>
  
  <h2>Suggestions in above questions</h2>
  
  <ul>
  <li>Change to .net 3.5, change target platform - these solutions could have serious issues with a large mult-project solution.</li>
  <li>HandleProcessCorruptedStateExceptions - does not work in C++, this decoration is for C#, catching this error could be a very bad idea anyway</li>
  <li>Change legacyCorruptedStateExceptionsPolicy - this is about catching the error, not preventing it</li>
  <li>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?)</li>
  <li>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. (<a href="http://connect.microsoft.com/VisualStudio/feedbackdetail/view/819552/visual-studio-debugger-throws-accessviolationexception" rel="nofollow noreferrer">http://connect.microsoft.com/VisualStudio/feedbackdetail/view/819552/visual-studio-debugger-throws-accessviolationexception</a>)</li>
  <li>Change Comodo Firewall settings - I don't use this software</li>
  <li>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.</li>
  <li>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.</li>
  <li>"Access violations in unmanaged code that bubble up to managed code are always wrapped in an AccessViolationException." - Fact, not a solution.</li>
  </ul>