Or at least I think the problem involves some kind of memory error. I'm making a program in SFML and I'm currently working on the menus using a GUI class that I made just for SFML. Internally, the GUI class uses std::shared_ptr to manage all of its internal pointers. The program consistently crashes after main() exits and all global destructors have been called, and gdb says a break point was triggered in ntdll!WaitForAlpCompletion, which leads me to believe that the problem is memory corruption. Whenever I remove the GUI instantiation from the menu function, it exits and closes with no errors. This seems to indicate GUI as the cause of the crash, except that sub-menus which create and destroy their own instances of GUI can be called and exited without any crashes or break points.
Some psuedocode:
SubMenu
{
Create GUI
Do Menu
Destroy GUI
}
Menu
{
Create GUI
Do Menu?SubMenu
Destroy GUI
}
main
{
Init Stuff
Menu
UnInit Stuff
Destroy GUI
return 0
}
//after return
Global Dtors
Breakpoint triggered???
I'm at a loss as to what this could be. I plan on using some memory debugger like valgrind sometime today, but I was wondering if anyone else had any ideas on what this could be.
Finally figured it out!!!!! It turns out that std::map calls the destructors of its objects every time it is re-sized, causing the shared_ptr's within to delete their data several times. A few "quick" design changes and fixed :) Thanks guys!
A heap corruption can be caused with this code:
int main()
{
int *A(new(std::nothrow) int(10));
int *B(A);
delete B;
delete A;
}
Does any of your code contain this similar situation?
Related
I write a piece of test code in VS2005 like this:
#include <stdio.h>
class Base {
public:
Base() {printf("Base +\n");};
~Base() {printf("Base -\n");};
char val[1024 * 1024 * 100];
};
void main()
{
Base *p = new Base();
return;
}
build, open a cmd window, then execute this console application.
open windows task manager to watch memory usage status.
I find two things:
1 the destructor is not called;
2 there is no memory leak from the windows task manager result.
is memory deleted by C++ runtime, or is it deleted by OS when the process exit? I just wonder the details about what happens to 100MB meory allocated in contructor after the main() return. If someone can tell me it is appreciated, and thanks.
After your program exits, the operating system will reclaim all used memory, whether or not delete has been called on it.
Other resources, like sockets, might take longer to be released by the operating system, but will eventually be reclaimed.
It will be up to the operating system.
However, things that you thought would go away when the app goes away tend to stay in memory longer than you thought. At some point, the code in main is moved to some function that gets called once. And then that function gets called multiple times. And then you have a leak. Better coding defensively in the first place than to fix problems later. Maybe years later.
Destructor not get called because you are not deleting your class B pointer.
Also after your application exits all the allocated resources get released irrespective whether you released it or not.
As with other answer, it's up to the operating system.
Having said this, it's usually well documented what will be clean up upon program termination.
This usually include application's private memory, files, sockets, resource handles, GUI resources, and may exclude resources that is global or shared amount many applications. (e.g. POSIX shared memory will persist until reboot if you do not call shm_unlink).
I have a QList of pointers objects which are inherited from QThread in a multi-threaded application. For example:
QList<Object*> m_threadList;
and
class Object: QThread
However, when all threads finished their execution, I need to delete those pointers in order to prevent memory leak. However it always crashed when the program tries to delete the pointer. The funniest thing is that it does not always happen. I am doing something like following:
for(QList<Object*>::iterator it=m_threadList.begin();it!=m_threadList.end();it++)
{
if(!(*it)->isRunning() && (*it)->isFinished())
{
disconnect((*it),SIGNAL(ResultsProvider(int)),this,SLOT(ResultsListener(int)));
(*it)->exit();
(*it)->deleteLater();
if((*it)!=NULL)
delete (*it); // It always crashes here
}
}
m_threadList.clear(); // will this cause an issue with deleteLater?
This crash does not happen always. Without changing anything, sometimes it will crash when it is trying to delete the pointer and sometimes it will go through smoothly. Has anybody faced similar problem before using any sort of container to store pointer objects (especially QThread)? or can anybody tell where can the problem be?
I am having problems with stack corruption in a new module I am working on which is part of a large legacy project. My code is written in C++ using Borland C++Builder 5.0.
I have tracked the problem to the following function:
// Note: Class TMarshalServerClientThread has the following objects defined
// CRITICAL_SECTION FCriticalSection;
// std::vector<TMarshalTagInfo*> FTagChangeQueue;
void __fastcall TMarshalServerClientThread::SendChangeNotifications()
{
EnterCriticalSection(FCriticalSection);
try {
if (FTagChangeQueue.size() == 0) {
return;
}
// Process items in change queue
FTagChangeQueue.clear();
} __finally {
LeaveCriticalSection(FCriticalSection);
}
}
This function is called in the context of a worker thread (which descends from TThread). A different thread populates the change queue with data as it becomes available. The change queue is protected by a critical section object.
When the code is run, I sporadically get access violations when attempting to leave the critical section. From what I can tell, sometimes when the __finally section is entered, the stack is corrupted. The class instance on the heap is fine, but the pointers to the class (such as the "this" pointer) appear to be invalid.
If I remove the call to return if the change queue is empty, the problem goes away. Additionally, the code to process the items in the queue is not the source of the problem, as I can comment it out and the problem remains.
So my question is are there known issues when using __finally in C++Builder 5? Is it wrong to call return from within a try __finally block? If so, why?
Please note that I realize that there are different/better ways to do what I am doing, and I am refactoring as such. However, I fail to see why this codes should be causing stack corruption.
As #duDE pointed, you should use pair of __try, __finally instead of intermixing C++ try, and Borland extension __finally.
I know it is a long time after the original question was posted, but as a warning to others, I can vouch for the symptom that Jonathan Wiens is reporting. I experienced it with Builder XE4. It does not happen frequently, but it seems that Borland/Embarcadero's implementation of try / finally blocks in a multi-threaded process very occasionally corrupts the stack. I was also using critical sections, although that may be coincidental.
I was able to resolve my problem by discarding the try / finally. I was fortunate that I was only deleting class instances in the finally block, so I was able to replace the try / finally with scope braces, using std::auto_ptr fields to delete the objects in question.
I am developing a gui proram using Qt 4.7.4 (64 bit). I have tried to isolate the problem as follows:
I have a window: class PreferencesWindow : public QMainWindow and in another class I initialize and show it as
QSharedPointer<PreferencesWindow> pPreferencesWindow = QSharedPointer<PreferencesWindow>(new PreferencesWindow());
pPreferencesWindow->show();
it is all good, then I close the window either by pressing ESC or clicking the x button on the window. And then I call
QApplication::quit();
to terminate the whole program. It terminates but gives a segmentation fault just before terminating.
The question here is why it terminates cleanly when I use regular pointer instead of QSharedPointer and how to use QSharedPointer properly in this case?
I suspect the problem is that when you close the window, the data structure pointed to by pPreferencesWindow is deleted without the QSharedPointer's knowledge. When the QSharedPointer itself is later destroyed, it double-deletes the window, and you get the segfault.
Basically, as with all shared pointer implementations, either everybody plays, or nobody does. Since the Qt internals will never know you're using a smart pointer to manage the window, you can't use one. This is a blessing in disguise, however; it means that Qt itself takes possession of the pointer and agrees to manage it for you, so you don't need a smart pointer after all!
I am not an expert with Qt but my first thoughts would be that QMainWindow deletes itself upon destruction and the QSharedPointer object will also delete the object when it's destroyed (i.e. the object is deleted twice). If this is true you don't need to use the QSharedPointer at all.
EDIT: It looks like the QtWidget Qt::WA_DeleteOnClose flag will cause the behaviour I have described.
I'm creating a pool of threads that cosumes a buffer and do some actions on my application. I've created a std::list m_buffer and sometimes the application crashes on the end of the buffer.
Here's my code:
MyObject* myObject = 0;
bool hasMore = true;
while(hasMore)
{
{
boost::unique_lock lck(m_loadMutex1);
if(!m_buffer.size())
break;
myObject = m_buffer.front();
m_buffer.pop_front();
hasMore = m_buffer.size();
}
}
if(myObject)
loadMyObject(myObject);
I'm sure the list never starts empty. And a lot of threads executes this piece of code at the same time. And testing it on Windows sometimes the application crashes and the debugger says it was on pop_front. But I can't believe its there because I check if the size is more than 0.
Thanks for helping.
Set first-chance exceptions in the debugger and see what the exception is that is being thrown.
I can't see a way that the code as posted would contain such a problem.
Most likely somewhere ELSE you're adding or removing from the list, unprotected, at the same time this function is popping.
Alternately there could be random memory corruption. Check the size of the buffer in the debugger when the pop_front fails.
I would review how the program terminates. Maybe the list has been deallocated. This could happen in a variety if ways. For example: the list is created on the main thread, the main thread finishes and deallocates the list, and the other threads are still using the list. I mention this particular example because I do not see any logic in the thread method above that lets each thread know it is 'shutdown' time.