I'm working on a Win32 application in C++ with Visual Studio 2010. When run in debug mode the application runs fine and closes properly upon exit. In release however, the program runs fine but upon application close there's an unhandled exception: Unhandled exception at 0x009C19F5 in Application.exe: 0xC0000005: Access violation reading location 0x00297628.
The debugger then breaks inside xlocale in std::local's destructor:
~locale() _THROW0()
{ // destroy the object
if (_Ptr != 0)
_DELETE_CRT(_Ptr->_Decref()); // breaks here with unhandled exception
}
The above code is being run, I believe, after my main function returns and exit( 0 ) is called somewhere. Here's my callstack upon crash:
Application.exe!std::locale::~locale() Line 411 C++
Application.exe!doexit(int code, int quick, int retcaller) Line 567 C
Application.exe!exit(int code) Line 393 C
Application.exe!__tmainCRTStartup() Line 284 C
kernel32.dll!#BaseThreadInitThunk#12() Unknown
ntdll.dll!___RtlUserThreadStart#8() Unknown
ntdll.dll!__RtlUserThreadStart#8() Unknown
I'm using Microsoft's application verifier and I'm running _CrtCheckMemory( ); often to check for heap corruption and I don't see any detected in either debug or release mode. I'm also not messing with std::locale at all in any of my source.
I recently switched the solution's settings to use unicode by default instead of 256 one byte sized characters. However switching back and forth now between unicode and multi-byte settings doesn't seem to affect the crash on exit in release.
Does anyone have any idea what's going on?
I've found the solution. There are some global variables calling new and I have new overloaded. When new is called for the first time a custom memory manager is constructed. This is fine, but on program close some objects destruct after the memory manager does. Order of destruction is what was causing the problems.
Another possible cause of a crash with identical symptoms is caused by a behaviour described by this subtle note:
Overload 7 (i.e. locale(const locale& other, Facet* f)) is typically called with its second argument, f, obtained directly from a new-expression: the locale is responsible for calling the matching delete from its own destructor.
This seems like implying that the locale will delete the facet only if it came from new, but in practice it doesn't. In other words, a locale was constructed from a facet that was not constructed by new, or was deleted earlier, causing the crash on the locale destructor's delete.
This can be fixed either by giving the locale proper absolute ownership of the facet, i.e. not deleting the facet manually or letting any smart pointers do it automatically (as well as ensuring that it actually was constructed via new), or, if modifying the facet is possible, overloading delete.
Related
So I have been playing around with chars and wide chars in a basic program that recursively scans directories in Windows. Initially I was using standard chars and strings, as well as some related functions for accomplishing this task (FindFirstFile, FindNextFile, etc.) The actual recursion is passed on to a created thread via CreateThread and WaitForSingleObject; which worked completely fine and as expected.
However, an issue arose when I converted those chars, strings, and related functions to their wide counterparts (wchar_t, wstring, FindFirstFileW, etc.) Now the program is throwing an exception when recursively scanning directories with more than a small number of folders/files. The exception is occurring during the WaitForSingleObject phase of my thread handling. I have tracked down the following info on the exception itself:
EAccessViolation is the exception class for invalid memory access
errors.
EAccessViolation is raised when an application:
Dereferences a nil (Delphi) or NULL (C++) pointer.
Writes to memory reserved for executable code.
Attempts to access a memory address for which there is no virtual
memory allocated to the application.
Run-time exception information is saved in fields provided by
EExternal.
Note: Applications should not raise EAccessViolation
directly, but should instead rely on the runtime to raise this
exception.
My question is, why on earth would this exception be thrown when the only thing I have changed is the type of characters being used? The IDE I am using is RAD Studio XE3 C++Builder and unfortunately, I can't really test this on one of my other IDEs without making significant changes to the code.
Hi I'm making a dialog based application in MFC using:
BOOL CClockMasterDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
m_ModeTabs.Create(this,WS_CHILD | WS_VISIBLE, 0);
}
If I destroy m_ModeTabs in CClockMasterDlg::OnInitDialog function after it is created using :
m_ModeTabs.DestroyWindow();
I get no memory but leaks when I place it in CClockMasterDlg::OnDestroy() I get memory leaks, even tough it gets called and returns true.
I don't believe that OnDestroy is OnInitDialog's contrary, but then which function is? There is no OnExitDialog.
Detected memory leaks!
Dumping objects ->
{601} client block at 0x00AEED48, subtype c0, 212 bytes long.
a CMFCVisualManager object at $00AEED48, 212 bytes long
Object dump complete.
The program [5312] ClockMaster.exe: Native has exited with code 2 (0x2).
Even tough the window should be destroyed automatically since it`s not a pointer I still shouldn't get memory leaks should I? And since placing
m_ModeTabs.DestroyWindow();
in the OnInitDialog function after its created solves the memory leak it cant really be something else causing the trouble can it? Removing the m_ModeTabs.Create(... Also solves the memory leak so I'm quite certain that its m_ModeTabs causing it.
Thought you don't say, I'm assuming that m_ModeTabs is a child window of your CClockMasterDlg. In that case, or similar cases, you don't have to explicitly call DestroyWindow. When a window is Destroy()ed by Win32, all of its child windows are destroyed as well.
Since you declared your m_ModeTabs as a regular variable (not a pointer), the memory owned by it will be freed automatically by the C++ runtime during the destructor of CClockMasterDlg.
I where actually hitting a bug which is gonna be "fixed in MFC for the next major release of Visual Studio".
The memory leak occurs when using a CVSListBox in a dialog only mfc application.
Information on the bug and several workarounds can be found here:
https://connect.microsoft.com/VisualStudio/feedback/details/646445/cvslistbox-produces-memory-leaks
http://connect.microsoft.com/VisualStudio/feedback/details/565327/memory-leaks-using-c
And another report on the bug here:
http://social.msdn.microsoft.com/Forums/en/vcgeneral/thread/8870974f-1414-4dd7-b7c3-a1c320c0e91e
Quotation from first link:
Hello,
Thanks for the report. This issue has been fixed in MFC for the next
major release of Visual Studio.
Pat Brenner Visual C++ Libraries Development
My developement environment is [Windows 7; visual studio 2010; x86].
I have a dll that was built for server 2003 long time back. When I use it in my project and follow new/delete sequence to use a class, application crashes during delete call. I verified the same even without any other call between new and delete. When I replace new/delete with malloc/free, there is no crash. If I simply declare an instance of the class without new, no crash happens when scope is exited.
Any idea what may be going wrong? This is internal library of our company, so I will not be able to name it and other such stuff.
Additional Information:
To use this library in first place, I had to turn off VS feature "Treat wchar_t as built-in type".
Code is simple
{
CLogger * myLog = new CLogger();
delete myLog; // Crash happens here
}
{ // No crash here
CLogger MyLog;
}
{
CLogger * myLog = (CLogger *) malloc (sizeof(CLogger));
free (myLog); // This does not crash.
}
This being proprietary library, I cannot post constructor and destructor.
delete does more than just freeing memory: it also calls the destructor before. That means that there must be something bad in the destructor of that class.
If an uncaught exception occurs in a destructor the whole process exits (*).
As commented below (thanks for the good feedback) this is over-simplified here is a good link for more details:
throwing exceptions out of a destructor
I would recommend you to put a
try {} catch (std::exception& e){} catch(...) {}
inside the destructor and log out what is going on, or better let it go through the debugger with the option to stop at the place where the exception is thrown.
Then it should be easy to identify what is different. Just a guess from me, it may be some registry access or file access rights, where some changes were introduced from server 2003 to windows 7.
I apply my psychic debugging skills to suggest that you are using delete where you should be using delete[].
Reasoning: if you were able to trivially replace new with malloc, you're probably allocating an array of primitive types rather than an object, and naively using delete in place of free on the assumption that object allocation and array allocation are the same in C++. (They're not.)
I wrote my own reference counted memory manager c++ (for fun) and I'm sure it isn't perfect ;) . And now when I'm trying to use it I got random SIGTRAP signals. If I comment out every line which are in connection with that memory manager everything runs fine. Getting SIGTRAP-s instead of SIGSEGV is quite strange.
I know that SIGTRAP-s are thrown when the program hits a breakpoint, but no breakpoint is set. I read in an other thread that debug builds of the exe's and dll's must be up to date. They are up to date and so it is not the reason.
Does anyone know why is this happening?
After searching on Google I realized that those sigtraps are same as those warnings you get in MSVC++ saying "Windows has triggered a breakpoint in xxxx.exe. This may be due to a corruption of the heap, and indicates a bug blahblahblah"...
So it seems yes, unexpected sigtraps can indicate memory corrupction (quite strange...)
And I found my bug too. The MM is in a static library which is linked to a dll. And that static lib and the dll is linked to my exe. So there were two memory managers, one in my exe and one in my dll. If call the initaialization method of the MM. It initialized the MM in my exe but not in the dll so the dll went without init. I solved this by not linking my exe against that static library.
I'd throw in a guess that you might be calling mismatched new/delete or malloc/free implementations - So something was allocated by your memory manager but when the memory is released you end up with the default delete/free implementation.
Set a breakpoint on the signal and see whether there is free() or operator delete on the stack and whether that is the implementation of said function which you would expect.
I have a program failing with:
terminate called after throwing an instance of 'std::bad_alloc'
what(): St9bad_alloc
I imagine it's something to do with malloc/free, but I don't know which one.
What breakpoint can I in gdb set that will break on the error so that I can view a stack trace?
The program is a combination of C and C++, compiled with gcc 3.4.2.
It is not really malloc/free which causes the exception, it is "new" which is definitely in C++ part of your application. It looks like you are providing a parameter which is too big for "new" to allocate.
'std::bad_alloc' is caused by the following code for example:
int * p = new int[50000000];
What does backtrace says when you load crash dump into gdb?
If you cannot generate dump, you can ask GDB to stop when exception is thrown or caught.
Unfortunately, some versions of GDB support only the following syntax:
catch throw
which allows you to break application when any exception is thrown.
However, in help you see that it should be possible to run
catch throw std::bad_alloc
in newer versions.
And don't forget that:
(gdb) help catch
is a good source for other useful information.
It's quite possible that this happens due to some memory being overwritten, thus corrupting the memory allocation system's state (which is generally kept either before or after the memory blocks returned to the application).
If you have the possibility (i.e., you're on x86 Linux), run your program in Valgrind, it can often show you exactly where the corruption happens.
I have had this when trying to read in a file that doesn't exist... I'd try to create an internal buffer for the file contents, but because the file didn't exist, my creation of the buffer screwed up.
int lenth_bytes;
length_bytes = in_file.tellg();
new char [length_bytes]; // length_bytes hadn't been initialised!!!!
Remember kids, always initialise your variables :D and check for zero cases.