Assertion when operator delete is called - c++

When my objects are destroyed, I keep getting an Assertion failure in
dbgheap.c line 1399
_ASSERTE(pHead->nBlockUse == nBlockUse);
I can't find any reason why this happens. The pointers are properly initialized to NULL in the constructor:
CPlayThread()
{
m_pPlayer[0]= NULL;
m_pPlayer[1]= NULL;
};
This is the code that actually creates the objects.
if(pParam->m_pPlayer[0] == NULL) //pParam is a CPlayThread*
{
if(config.m_nPlayerMode == modeSocket)
pParam->m_pPlayer[0]= new CSocketPlayer();
}
The objects get destroyed when the thread is destroyed, and this is where the assertion occurs.
~CPlayThread()
{
if(m_pPlayer[0])
delete m_pPlayer[0];
m_pPlayer[0]=NULL;
if(m_pPlayer[1])
delete m_pPlayer[1];
m_pPlayer[1]= NULL;
};
I'm at a total loss here. It used to work fine and somehow it started crashing at a client's location after three or four days of running continously. At the same time my debug executable started asserting every
single time a player was destroyed. There are up to 96 threads that might be playing at any given time (with two players each thread, alternating - the players were created and destroyed as needed). So after looking for a solution and not finding one, I decided to just keep the objects for the duration of the application exectution. So now I only get the assertion when I close the debug version of the program (and presummably there is an unnoticeable crash on closing the release version, which is never because this should run 24/7).
I just need to know what I am doing wrong. Any help would be appretiated.

What type is m_pPlayer[0] ( Like David asked. ) is it a base type of CSocketPlayer or is it CSocketPlayer itself. ? If it's a base type you need to make the destructor in the base class virtual. That might be related to your problem. If not, then the problem must be that you already deleted the object. This can be due to a racing condition, where 2 threads run the destructor with the same pointers.
What also could be is that either the new or delete operator is overloaded, for example allocating from another heap. Guess that is far fetched .... but possible ..

Related

Weird crashes in C++ Project on thread.join()

i have written a chess engine which plays at a high level. Unfortunately we are known for multiple engine crashes. There are a few people trying to figure out the reason for those crashes. The code can be found here. We tracked all crashes we encountered down to one file which deals with all the input/output from/to the user. uci.cpp is the file.
The job of uci.cpp/h is to implement the universal chess protocol (uci). For that purpose we have some global Board object which represents a position. To be able to receive a stop command while the engine searches a specific position, we brought the search into its own thread. We use thread.joinable() to check if a search is still running and searchThread.join() before we start a new search to make sure we do not have multiple searches running.
Someone has sent us the list of crashes he was able to provoke on his machine:
1a) general protection fault on libstdc++.so.6.0.28, thread::join crash
1b) segfault on libpthread-2.31.so (replace 2.31 by your libc version), also thread::join crash
2a) trap stack segment on the binary itself, delete board crash
2b) segfault on the binary itself, delete board crash
Error type 1/2: thread.join()
The first 2 crash types are both related to calling searchThread.join() although we check if its joinable.
void uci_stop() {
search_stop();
if (searchThread.joinable()) {
searchThread.join();
}
}
What are reasons that could .join() to fail?
We analysed our code a while ago and were not able to find any memory leaks. As far as we know, all data that is allocated within the searchThread will also get deleted.
Error type 3/4: delete board;
We use a global pointer for the board and in very rare instances, deleting that pointer will fail.
I found a potential solution which will statically allocate the board object globally which means I wouldnt havent to use new and delete anymore.
// old:
Board* board;
// new:
Board board{""};
We think that this solves the problem and is not the main part of this question although we are still curious why delete board could fail in some instances.
All crashes have only occured in roughly 2% of all games. With a game taking about 60 moves, thread.join() fails about 1 in 1000 times.

Failed to release Direct3D Device "or" Corresponding Context

Yes, its actually "or". I shall explain. I am developing helper classes for myself, like DirectXToolKit. For managing COMs I`m using Microsoft::WRL::ComPtr<T> (wrl.h).
struct Renderer
{
ComPtr<ID3D11Device> m_Device;
ComPtr<ID3D11DeviceContext> m_ImmContext;
}
When all the resources are destroyed, the instance of the structure above should be destroyed as well, but after the dtor is called, I am triggering the error in Microsoft::WRL::ComPtr<T>, when it tries to release the device or context.
I have implemented the dtor where I manually release m_Device and m_ImmContext, but unfortunately the last member I try to release always encounters an issue in the function
unsigned long InternalRelease() throw()
{
unsigned long ref = 0;
T* temp = ptr_;
if (temp != nullptr)
{
ptr_ = nullptr;
ref = temp->Release();
}
return ref;
}
here
ref = temp->Release();
When I succeed releasing the device first, the context triggers the error, and vice versa (! yes, when one of them was successfully released, the destuction of the second member fails). There was already a question like mine (destroy directx device and swap chain), but the window and swapchain are already destroyed, like the other dx resources. Have no clue why is this happening. Any ideas?
Sorry for my imperfect English :3
I have fixed this issue. The problem was I have not understood std::shared_ptr good enough (the function std::make_shared actually (about shared pointers and their allocation)):
I have created the pointer like:
Obj *ObjPtr = new Obj();
and then just:
SomeOtherState.SharedObj = std::make_shared<Obj>(*ObjPtr);
and didn`t destroy the ObjPtr afterwards. The data ObjPtr was pointing on was still in memory, after SomeOtherState was destroyed (and as far as I have understood the issue should have gone as well if I have used the std::shared_ptr ctor) .
Most likely it was because of this memory leak, but there was another thing I have changed: CoUninitialize call was made before the last COM pointer was destroyed but from MSDN: CoUninitialize came that its important (from the first para actually):
Closes the COM library on the current thread, unloads all DLLs loaded by the thread, frees any other resources that the thread maintains, and forces all RPC connections on the thread to close.
So I have replaced CoInitialize and CoUninitialize correspondently and the issue have gone. If someone had had the same troubles, this could somewhat be a solution (either or both the first and the second change I have made).
I should probably add "com" tags for my question
the problem MAY be somewhere when you obtain the ImmediateContext.
According to the documentation:
http://msdn.microsoft.com/en-us/library/windows/desktop/ff476529%28v=vs.85%29.aspx
The GetImmediateContext method increments the reference count of the immediate
context by one. Therefore, you must call Release on the returned interface pointer
when you are done with it to avoid a memory leak.
So I >>>guess<<< that you've forgot releasing the context somewhere so the Device release fails afterwards.
BTW: Make also sure that resources are ALWAYS released in reverse order.

C++ Ref Count Changes While Destructing Object

I've got a private ref count inside the class SharedObject. SharedObject is a base class for other classes, for example Window. Window is the base class of Editor.
When the ref count reaches 0, because of calling SharedObject::Release(), the SharedObject deletes itself. First we get to the Editor destructor, which shows that the this pointer contains m_refs == 0, but when we get to the Window destructor it is suddenly 1, and when we reach the SharedObject destructor, it is still 1.
I put a breakpoint on the SharedObject::IncRef() method, and it was never called while this happened.
What the?
Build with optimizations off, and set a memory breakpoint on your m_refs.
Seems like you have memory leak somewhere, maybe even long before this destruction occurs. I use Alleyoop to find leaks. Can help, won't hurt to have that out of the way.
Do you use multiple threads? Maybe it's due to some raw pointer somewhere being grabbed by other thread during destruction.
On a side note, I recommend using boost::intrusive_ptr - very convinient pattern for handling addrefs and releases in shared objects that helps to be consequent with it, but this probably won't solve your problem unless you have a real mess in your code ;)

Qt C++ destructor taking a long time to return

I'm working on a pretty standard Qt mobile app (written in C++, targeted at Symbian devices), and am finding that sometimes when the app is closed (i.e. via a call to QApplication::quit), the final destructor in the app can take a long time to return (30 seconds plus). By this I mean, all clean up operations in the destructor have completed (quickly, all well within a second) and we've reached the point where execution is leaving the destructor and returning to the code that implicitly called it (i.e. when we delete the object).
Obviously at that point I'd expect execution to return to just after the call to delete the object, virtually instantly, but as I say sometimes this is taking an age!
This long closure time happens both in debug and release builds, with logging enabled or disabled, so I don't think that's a factor here. When we reach the end of the destructor I'm pretty certain no file handles are left open, or any other open resources (network connections etc.)...though even if they where surely this wouldn't present itself as a problem on exiting the destructor (?).
This is on deleting the application's QMainWindow object. Currently the call to do this is in a slot connected to QApplication::aboutToQuit, though I've tried deleting that object in the apps "main" function too.
The length of delay we experience seems proportional to the amount of activity in the app before we exit. This sort of makes me think memory leaks may be a problem here, however we're not aware of any (doesn't mean there aren't any of course), and also I've never seen this behaviour before with leaked memory.
Has anyone any ideas what might be going on here?
Cheers
If your final destructor is for a class than inherits QObject then the QObject destructor will be called immediately following the destructor of your final object. Presumably this object is the root of a possibly large object tree which will trigger a number of actions to occur including calling the destructor of all the child QObjects. Since you state that the problem is componded by the amount of activity, there are likely a very large number of children being added to the object tree that are deleted at this time, perhaps more than you intended. Instead of adding all the objects to one giant tree to be deleted all at once. Identify objects that are being created often that don't need to persist through the entire execution. Instead of creating those objects with a parent, start a new tree that can be deleted earlier (parent =0). Look at QObject::deleteLater() which will wait until there is no user interaction to delete the objects in these independant trees.

Questions about C++ memory allocation and delete

I'm getting a bad error. When I call delete on an object at the top of an object hierarchy (hoping to the cause the deletion of its child objects), my progam quits and I get this:
*** glibc detected *** /home/mossen/workspace/abbot/Debug/abbot: double free or corruption (out): 0xb7ec2158 ***
followed by what looks like a memory dump of some kind. I've searched for this error and from what I gather it seems to occur when you attempt to delete memory that has already been deleted. Impossible as there's only one place in my code that attempts this delete. Here's the wacky part: it does not occur in debug mode. The code in question:
Terrain::~Terrain()
{
if (heightmap != NULL) // 'heightmap' is a Heightmap*
{
cout << "heightmap& == " << heightmap << endl;
delete heightmap;
}
}
I have commented out everything in the heightmap destructor, and still this error. When the error occurs,
heightmap& == 0xb7ec2158
is printed. In debug mode I can step through the code slowly and
heightmap& == 0x00000000
is printed, and there is no error. If I comment out the 'delete heightmap;' line, error never occurs. The destructor above is called from another destructor (separate classes, no virtual destructors or anything like that). The heightmap pointer is new'd in a method like this:
Heightmap* HeightmapLoader::load() // a static method
{
// ....
Heightmap* heightmap = new Heightmap();
// ....other code
return heightmap;
}
Could it be something to do with returning a pointer that was initialized in the stack space of a static method? Am I doing the delete correctly? Any other tips on what I could check for or do better?
What happens if load() is never called? Does your class constructor initialise heightmap, or is it uninitialised when it gets to the destructor?
Also, you say:
... delete memory that has already been deleted. Impossible as there's only one place in my code that attempts this delete.
However, you haven't taken into consideration that your destructor might be called more than once during the execution of your program.
In debug mode pointers are often set to NULL and memory blocks zeroed out. That is the reason why you are experiencing different behavior in debug/release mode.
I would suggest you use a smart pointer instead of a traditional pointer
auto_ptr<Heightmap> HeightmapLoader::load() // a static method
{
// ....
auto_ptr<Heightmap> heightmap( new Heightmap() );
// ....other code
return heightmap;
}
that way you don't need to delete it later as it will be done for you automatically
see also boost::shared_ptr
It's quite possible that you're calling that dtor twice; in debug mode the pointer happens to be zeroed on delete, in optimized mode it's left alone. While not a clean resolution, the first workaround that comes to mind is setting heightmap = NULL; right after the delete -- it shouldn't be necessary but surely can't hurt while you're looking for the explanation of why you're destroying some Terrain instance twice!-) [[there's absolutely nothing in the tiny amount of code you're showing that can help us explain the reason for the double-destruction.]]
It looks like the classic case of uninitialized pointer. As #Greg said, what if load() is not called from Terrain? I think you are not initializing the HeightMap* pointer inside the Terrain constructor. In debug mode, this pointer may be set to NULL and C++ gurantees that deleting a NULL pointer is a valid operation and hence the code doesn't crash. However, in release mode due to optimizations, the pointer in uninitialized and you try to free some random block of memory and the above crash occurs.