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
Is std::vector copying the objects with a push_back?
std::string in struct - Copy/assignment issues?
http://www.cplusplus.com/reference/vector/vector/operator=/
Assign one struct to another in C
Why this exception is not caught by my try/catch
https://stackoverflow.com/a/918891/2091951
Generic AccessViolationException related questions
How to handle AccessViolationException
Programs randomly getting System.AccessViolationException
https://connect.microsoft.com/VisualStudio/feedback/details/819552/visual-studio-debugger-throws-accessviolationexception
finding the cause of System.AccessViolationException
https://msdn.microsoft.com/en-us/library/ms164911.aspx
Catching access violation exceptions?
AccessViolationException when using C++ DLL from C#
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.
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.
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.
You seem to have memory corruption. Microsoft Application Verifier is invaluable in finding corruption. Use it to find your bug:
Install it to your dev machine.
Add your exe to it.
Only select Basics\Heaps.
Press Save. It doesn't matter if you keep application verifier open.
Run your program a few times.
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.
I'm trying to copy a wide c-string from one place into another. I'm using Visual Studio 2012 express on windows8 64-bit platform. It works perfectly fine unless i try to run the application on my main computer with Windows7 x64. It crashes instantly. No exception error though it's a messy crash with no trackable error code whatsoever. If you need more specific information about the crash itself i will try to provide it. When i comment out the copying the program works perfectly fine. So it's pretty obvious the problem is with the function itself. Here is the line that does all the copying:
virtual void CClass::ChangeText();
void CClass::ChangeText(float _f)
{
std::wstringstream wss;
wss << _f;
wcscpy(const_cast<wchar_t *>(this->m_lpszWideText),wss.str().c_str());
}
^ crashes on win7 / works on win8
My wild guess is that the new compiler uses a newer version of wmemcpy that just doesn't work on windows 7? Shouldn't the program crash only when it reaches the function call line though?
A Crash with String-Copy algorithms have usually two origins:
Your Source is not NULL-Terminated
In Your Example this is not the case, because you extract it from wstringstream::c_str()
Your Destination is not big enough to handle the source data, and so is written out of Bounds.
This may be the cause of your Crash, means, your this->m_lpszWideText is too small (please give the Declaration of it and, if it is dynamically allocated show us, how.)
Is there a function available that can get the number of blocks of memory that are currently allocated on the heap? It can be Windows/Visual Studio specific.
I'd like to use that to check if a function leaks memory, without using a dedicated profiler. I'm thinking about something like this:
int before = AllocatedBlocksCount();
foo();
if (AllocatedBlocksCount() > before)
printf("Memory leak!!!");
There are several ways to do it (specific to the CRT that comes with Microsoft Visual Studio.)
One way would be to use the _CrtMemCheckpoint() function before and after the call you are interested in, and then compare the difference with _CrtMemDifference().
_CrtMemState s1, s2, s3;
_CrtMemCheckpoint (&s1);
foo(); // Memory allocations take place here
_CrtMemCheckpoint (&s2);
if (_CrtMemDifference(&s3, &s1, &s2)) // Returns true if there's a difference
_CrtMemDumpStatistics (&s3);
You can also enumerate all the allocated blocks using _CrtDoForAllClientObjects(), and a couple of other methods using the debug routines of the Visual C++ CRT.
Notes:
All these are in the <crtdbg.h> header.
They obviously work only on Windows and when compiling with VC.
You need to set up CRT debugging and a few flags and other things.
These are rather tricky features; make sure to read the relevant parts of the MSDN carefully.
These only work in debug mode (i.e. linking with the debug CRT and the _DEBUG macro defined.)
I'm using Oracle Solaris Studio for some memory tests. I just installed it, and wrote the traditional "Hello World" program to make sure all is up and running correctly.
However, the Memory leaks tool reports that operator new is leaking 40 bytes...
I read that this was a common problem in older versions of visual studio with the MFC (Microsoft Foundation Classes) but now I'm very confused because this in an Oracle product... right?
As I understand it can be ignored. But it is annoying to see it pop up every time just because I print something.
Can something be done about it?
Thanks.
Here is the code:
#include <iostream>
int main(void)
{
std::cout<<"Hello World\n";
return 0;
}
I compiled with Sun Studio 12 and examined with TotalView:
There is indeed a heap allocation of 40 bytes without a matching deallocation, made by __rwstd::facet_imp* __rwstd::facet_maker<std::codecvt<char,char,__mbstate_t>>::maker_func( int, const char*, unsigned ), called by __rwstd::facet_imp* std::locale::__make_explicit( const std::locale::id& ,bool, int, __rwstd::facet_imp*(*)(int,const char*,unsigned)) const, called by filebuf::overflow called by filebuf::sync called by operator<<.
Note though that Oracle recommends compiling with -library=stlport4 unless you need binary compatibility with something built against their roguewave-based libCstd. Compiled with this option, there are no heap allocations made in main() at all.
I've tried the Solaris Studio memory tool and found it to be quite helpful... and accurate, even when I thought I knew my code better than the tool. Perhaps the people who were so quick to denigrate the Solaris Studio Memory Tool would be willing to give it a try to see how much better it is than the suggested alternatives.
Purify from IBM can detect memory leak, maybe you can try it.
I'm having a very strange problem when trying to run RapidXml 1.13 under Windows CE 6.0 compiled with Visual Studio 2005. I have an extremely small program that fails to run:
#include <rapidxml.hpp>
using namespace rapidxml;
int _tmain(int argc, _TCHAR* argv[])
{
xml_document<char> doc;
return 0;
}
It compiles fine with 0 errors and 0 warnings (at W3). However, when I run or debug the program, I get an access violation exception:
First-chance exception at 0x000110d4 in RapidXml_Test.exe:
0xC0000005: Access violation writing location 0x0001fb48.
The debugger then points to this line (1366 in rapidxml.hpp) as the culprit (the open brace):
template<class Ch = char>
class xml_document: public xml_node<Ch>, public memory_pool<Ch>
{
public:
//! Constructs empty XML document
xml_document()
: xml_node<Ch>(node_document)
------->{
}
...
If anyone has any clue what the problem could be I'd greatly appreciate it. I have much more complicated code working in my build and run-time environment so I don't suspect anything there. I'm also fairly confident it's not a project setting. I assume at this point that RapidXml's use of templates is somehow confusing the Windows CE VC++ compiler. I don't know what else it could be.
Thanks in advance!
I found the solution. RapidXML allocates its own pool of memory once its loaded. Problem is, I think it allocates it on the stack and I was getting a stack overflow! (How serendipitous that the problem with my first question here actually WAS a stack overflow). Anyways, reducing the size of the pool solved my problem.