mfc >> Application crashes when closed

by UHVuaXQgS2F1cg » Thu, 10 May 2007 00:31:03 GMT

Hi,

I have a windows application written using MFC , VC++ 6.0, I am using the
Application Verifier debugging tool to solve some bugs in my application.
When running in debug mode with the Application Verifier running in the
background, the application crashes when I close it. I have overriden the
OnClose method to do the following :

void CRecorder6Dlg::OnClose()
{
char HeaderID[MAX_UID_LEN +10];
char TxIP[20]; //change
CFileFind finder;
SHORT TimeOut = 0;
SYSTEMTIME Timey ; //System time structure
PSYSTEMTIME Ptr2;
Ptr2 = &Timey;
char cDate[11];
char cTime[9] ;

GetLocalTime(Ptr2);
sprintf(cDate,"%04d%c%02d%c%02d",Timey.wYear,'-',Timey.wMonth,'-',Timey.wDay);
sprintf(cTime,"%02d%c%02d%c%02d",Timey.wHour,':',Timey.wMinute,':',Timey.wSecond);

if (MessageBox("Are you sure you want to exit?","Shutdown?",MB_YESNO |
MB_ICONEXCLAMATION) == IDYES)
{
ClosingDown = true;

BeginWaitCursor();
StatbarR.SetText("Closing................. ",0,0);
SaveKeyset();
timeKillEvent(timer_number);

Sleep(300);
RNBOsproReleaseLicense(spro_packet,0,0);

TimeOut = 0;
threadrecvlive = FALSE;
ThreadOTARLive = FALSE;
threadDBlive = FALSE;
StatbarR.SetText("Stopping Receive Thread................. ",0,0);
while (!threadrecvlive && (TimeOut < 100))
{
Sleep(30);
TimeOut++;
}

TimeOut = 0;
StatbarR.SetText("Stopping OTAR Thread................. ",0,0);
while (!ThreadOTARLive && (TimeOut < 10))
{
Sleep(30);
TimeOut++;
}

TimeOut = 0;
StatbarR.SetText("Stopping Database Thread................. ",0,0);
while (!threadDBlive && (TimeOut < 10))
{
Sleep(30);
TimeOut++;
}

//Shut down Playthread thread
TimeOut = 0;
threadplaylive = FALSE;
StatbarR.SetText("Stopping Playback Thread................. ",0,0);
while(!threadplaylive && TimeOut< 50)
{
Sleep(30);
TimeOut++;
}

//Shut down "Get Disk Size" thread
TimeOut = 0;
threadGetSpace = FALSE;
StatbarR.SetText("Stopping Diskspace-Check Thread................. ",0,0);
while(!threadGetSpace && TimeOut< 50)
{
Sleep(30);
TimeOut++;
}

//Close any left open files

memset(HeaderID,0,sizeof(HeaderID));//Null array
sprintf(HeaderID,"%-s","ID Recorder Terminated ");//ANI tag-> ID
memset(TxIP,0,sizeof(TxIP));//Null array,No IP info on Rx //change
sprintf(TxIP,"%-s","IP"); //ADD IP Tag //change
for (int i=1; i<=MAX_CHANS; i++)
{
if(prx[i]->bFileOpen_File_Compr)
{
mmioWrite(prx[i]->File_Compr,(HPSTR)HeaderID,MAX_UID_LEN);//Write empty
ANI to PCM file
mmioWrite(prx[i]->File_Compr,(HPSTR)TxIP,sizeof(TxIP)); //Write empty IP
to PCM File //change
mmioClose(prx[i]->File_Compr,NULL);

}
if(ptx[i]->bFileOpen_File_Compr)
{
mmioWrite(ptx[i]->File_Compr,(HPSTR)HeaderID,MAX_UID_LEN);//Write empty
ANI to PCM file //change
mmioWrite(ptx[i]->File_Compr,(HPSTR)TxIP,sizeof(TxIP));//Write IP to PCM
file
mmioClose(ptx[i]->File_Compr,NULL);

}
}

//Compress remaining PCM files

if (BOOL bWorkingClose = finder.FindFile(cFolderTelwave))
{
StatbarR.SetText("Compressing Files, Please
Wait................................. ",0,0);//Ver 1.1.0
while (bWorkingClose)
{
Sleep(30);//Ver 1.1.0
bWorkingClose = finder.FindNextFile();
bWorkingClose = finder.FindFile(cFolderTelwave);
}
}
finder.Close();

//Shut down Compression thread
TimeOut = 0;
threadComPress = FALSE;
StatbarR.SetText("Stopping Compression Thread................. ",0,0);
while(!threadComPress && TimeOut< 50)
{
Sleep(30);
TimeOut++;
}


//Clean up Rx and Tx class pointers
StatbarR.SetText("Closing................. ",0,0);
for (int p=1; p<=MAX_CHANS; p++)
{
prx[p]->teardown(p);
if (prx[p]!=NULL)
{
delete prx[p];
}
ptx[p]->teardown(p);
if (ptx[p]!=NULL)
{
delete ptx[p];
}
mic[p]->teardown(p); //error line
if (mic[p]!=NULL)
{
delete mic[p];
}
}


//Close DataBase
if (!TelexDB.IsOpen())
{
TelexDB.Close();
}

CompressClose(); //Close compresion stuff
Statbar_fontR.DeleteObject();//Delete font object
EndWaitCursor();
CDialog::OnClose();
DestroyWindow();

//Adding "Network Recorder Closed" entry to the Date_timeLog.txt file
ofstream out("C:\\Program Files\\Telex
Vega\\LogFiles\\Date_TimeLog.txt",ios::app); // Open for writing
out << "Network Recorder closed\t" << cDate<<"\t"<<cTime<<"\n";
}

}

I crashes at the line : see for "//error line "above. Tear down is a user
defined function, and it fails in the setsockopt function

setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP,(char FAR
*)&mreq,sizeof(mreq)); which is called inside teardown.

When I verified the value of sock, the value was 000000 and I thought that
was the cause of it. I commented out that line and it started throwing error
in the previous line's tear down function. I commented out everything in the
for loop and now it gives me another error .

<avrf:message>Unloading DLL containing an active critical
section.</avrf:message>
<avrf:parameter1>10103944 - Critical section address.</avrf:parameter1>
<avrf:parameter2>0 - Critical section initialization stack
trace.</avrf:parameter2>
<avrf:parameter3>1730fe8 - DLL name address.</avrf:parameter3>
<avrf:parameter4>10000000 - DLL base address.</avrf:parameter4>
- <avrf:stackTrace>
<avrf:trace>vfbasics!VfBasicsStopMessage+8e</avrf:trace>
<avrf:trace>vfbasics!AVrfpFreeMemLockChecks+17c</avrf:trace>
<avrf:trace>vfbasics!AVrfpFreeMemNotify+39</avrf:trace>
<avrf:trace>vfbasics!AVrfpDllUnloadCallback+2c</avrf:trace>
<avrf:trace>ntdll!RtlQueryProcessDebugInformation+117e</avrf:trace>
<avrf:trace>ntdll!RtlInitializeSListHead+44c4</avrf:trace>
<avrf:trace>vfbasics!AVrfpLdrUnloadDll+73</avrf:trace>
<avrf:trace>kernel32!FreeLibrary+19</avrf:trace>
<avrf:trace>ODBC32!SQLErrorA+1b4</avrf:trace>
<avrf:trace>ODBC32!SQLFreeEnv+1d</avrf:trace>
<avrf:trace>MFCD42D!CDatabase::Free+fb</avrf:trace>
<avrf:trace>MFCD42D!CDatabase::~CDatabase+47</avrf:trace>
<avrf:trace>Recorder!$E303+d</avrf:trace>
<avrf:trace>MSVCRTD!doexit+6f</avrf:trace>
<avrf:trace>MSVCRTD!exit+10</avrf:trace>
<avrf:trace>Recorder!WinMainCRTStartup+1c0</avrf:trace>
<avrf:trace>kernel32!RegisterWaitForInputIdle+49</avrf:trace>

Another imp piece of information: When I try to build my project in Debug
mode, I get two warnings all the time:

LINK : warning LNK4098: defaultlib "LIBCMT" conflicts with use of other
libs; use /NODEFAULTLIB:library
LINK : warning LNK4098: defaultlib "MSVCRT" conflicts with use of other
libs; use /NODEFAULTLIB:library

I tried to add /NODEFAULTLIB:MSVCRTD.LIB and LIBCMTD.LIB in ignore files in
my Project settings under Link tab. But it was of no use.

Are these problems interlinked? I read somewhere that such warnings can give
rise to problems while freeing memory which I am doing in Onclose function.

Please suggest.


mfc >> Application crashes when closed

by AliR (VC++ MVP) » Thu, 10 May 2007 00:44:43 GMT


ot really sure where you crash is, you need to narrow it down to a few
lines or something.

But I have a question, are your threads GUI threads or Worker threads?

AliR.



"Punit Kaur" < XXXX@XXXXX.COM > wrote in message
news: XXXX@XXXXX.COM ...





mfc >> Application crashes when closed

by AliR (VC++ MVP) » Thu, 10 May 2007 00:47:10 GMT

houldn't your loop with the error look like this


AliR.

"AliR (VC++ MVP)" < XXXX@XXXXX.COM > wrote in message
news:ZWm0i.2126$ XXXX@XXXXX.COM ...




RE: Application crashes when closed

by TWFyayBTYWxzYmVyeQ » Thu, 10 May 2007 00:55:01 GMT

You use objects and THEN check to see if they are NULL?

prx[p]->teardown(p);
if (prx[p]!=NULL)
... }
mic[p]->teardown(p); //error line
if (mic[p]!=NULL)

Are either of these NULL when used?

In the teardown() functions, are ay objects being used that have already
been destroyed?

Mark



Application crashes when closed

by UHVuaXQgS2F1cg » Thu, 10 May 2007 01:04:02 GMT

his application was coded by someone else. For some reason he started
storing values from 1 to MAX_CHANS in some other function. Also, the threads
are worker threads.


"AliR (VC++ MVP)" wrote:



RE: Application crashes when closed

by UHVuaXQgS2F1cg » Thu, 10 May 2007 01:50:02 GMT


ok.. Half of the problem seems to be solved. I checked the code and saw that
in the function

setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP,(char FAR

sock handle value being passed was 0 since for some cases we were
initializing sockets and for some we were not. But we were tryin to close all
the sockets, irrespective of whether they were initiialized . I changed the
code to check that and now it no longer gives error on that line.

But the other error still exists while closing the application "Unloading
DLL containing an active critical.

When I do step wise exec, The Onclose function successfully executes and
closes the window without any problem and then goes thru some stmts in
CMDTARG.CPP, DLGCORE.CPP, and then WINCORE.CPP and after it executes some
stmt in WindowProc method, it goes to disassembly and calls a user break
point.

The xml file that I attached in the previous post is the log file produced
by Application verifier for this bug. How should i solve it? Does it have
anything to do with how my libraries have been linked and the warnings that I
am getting. This application is a multithreaded app.








RE: Application crashes when closed

by TWFyayBTYWxzYmVyeQ » Thu, 10 May 2007 02:36:01 GMT

> But the other error still exists while closing the application "Unloading

I'm not aware of what exactly this message means but by reading it I wonder
- is there a thread still running that is trying to take ownership of a
critical section while another thread owns it (has not called
LeaveCriticalSection()) ?

Mark



Application crashes when closed

by Joseph M. Newcomer » Thu, 10 May 2007 02:46:35 GMT

here are massive number of things wrong here, any one of which could lead to a crash. See
below...
On Wed, 9 May 2007 09:31:03 -0700, Punit Kaur < XXXX@XXXXX.COM > wrote:

*****
Define "crash". THe word itself is essentially a content-free noise word unless it is
accompanied by a PRECISE description of what happened! Access fault? Stack overflow?
Assertion failure? Without anything meaningful here, there is no way to guess what has
gone wrong, or what you mean by the noise word "crash"
*****
****
Why a char and not a CString? This is not Unicode-aware, and any buffer overflow in any
of these rather quaint fixed-size buffers will kill you
*****
****
CString
****
*****
Why do you need a variable which holds a pointer? This is immediately suspect as a
programming style
****
****
CString.
****
*****
CString
****
*****
Didn't you ever hear of the & operator? For example
GetLocalTime(&Timey);
would be the right way to write this, eliminates the pointless (pun intended) pointer
variable
*****
****
There are so many things wrong here that it is mind-boggling. If anything goes wrong in
this printout, your program will die a horrible, horrible death. Oh wait, it's doing that
already...
cDate.Format(_T("%04d-%02d-%02d"), Timey.wYear, Timey.wMonth, Timey.wDay);
cTime.Format(_T("%02d:%02d:%02d"), Timey.wHour, Timey.wMinute, Timey.wSecond);

you don'thave to provide the punctuation marks as %c formatting of literal values; that's
just silly.
*****
*****
Why the gratiuitous sleep? If it has to be there, your program is already wrong, so fix
the reason it is wrong and get rid of ths trash.
*****
*****
See previous comment about sleep. This is a horrific structure for detecting if a thread
has finished. Either WaitForSingleObject on the thread handle or better still implement a
completley asynchronous shutdown mechanism. This is just trash. Lose it all.
*****
****
Ditto.
****
*****
Ditto
****
*****
Ditto
****
*****
DItto

Note that if any of these threads FAILS to stop in the minuscle time you allotted, your
program will probably die a horrible death. Oh wait, it's already doing that!
*****
****
memsets scare me. In any case, ::ZeroMemory would be a better choice
*****
*****
CString TxIP;
TxIP.Format(_T("%-s"), _T("IP"));
I presume in this case that the literal "IP" is a placeholder for something that is not
yet computed.

Essentially, assume if you use fixed character buffers and sprintf that your program is
intrinsically flawed, and will crash due to buffer overruns. Take this as a given. The
number of times you ever need to use sprtinf in any real program is so vanishingly small
as to be indistinguishable from 0.
*****
*****
See comments about sleep
****
****
See comments about sleep
****
*****
THis looks deadly right here. At this point, you need to figure out why you are unloading
a DLL that has an active critical section! Until this is solved, there isn't much else to
discuss. I would not at all be surprised if that bizarre attempt to shut down the threads
was malfunctioning and led to this situation.

You need to resolve all threading issues first. I can think of a whole bunch of things
that code like this can lead to, none of them good. You need to rewrite the shutdown
sequence and make it an asynchronous shutdown sequence. Otherwise, you are going to
continue to be plagued with problems.

*****
****
T

RE: Application crashes when closed

by UHVuaXQgS2F1cg » Thu, 10 May 2007 02:54:01 GMT


I thought that was possible and I commented the thread code. No threads are
being spawned in my application now. Commented out all the AfxBeginThread
code. Now I have only three lines in my OnClose function

if (!TelexDB.IsOpen())
{
TelexDB.Close();
}
CDialog::OnClose();
DestroyWindow();

Same error!!!







Application crashes when closed

by TWFyayBTYWxzYmVyeQ » Thu, 10 May 2007 03:00:01 GMT

Hi Joe,

You forgot these...

prx[p]->teardown(p);
if (prx[p]!=NULL)
{
delete prx[p];
}
ptx[p]->teardown(p);
if (ptx[p]!=NULL)
{
delete ptx[p];
}
mic[p]->teardown(p); //error line
if (mic[p]!=NULL)
{
delete mic[p];
}

:)

I enjoy your articles- I've seen many of them liked to on CodeProject.

Cheers!
Mark




Application crashes when closed

by UHVuaXQgS2F1cg » Thu, 10 May 2007 03:30:01 GMT


Any pointers on how to solve these warnings? For debug mode, I have the
following selected...In my project settings under C,C++ Code Generation- use
runtime library: Debug Multithreaded DLL . What else do I need to change? Any
link where it clearly describes the Visual Studio project settings for a
multithreaded app?




LINK : warning LNK4098: defaultlib "LIBCMT" conflicts with use of other
****
These are serious errors. You have somehow messed up your linker commands.
THis is
clearly a multithreaded app, and you may well have loaded the
single-threaded library.
THere is little point to even running the program until these two messages
are corrected.
*****


Application crashes when closed

by Joseph M. Newcomer » Thu, 10 May 2007 09:54:12 GMT

Probably caused by a failure to wait for proper thread shutdown.
joe




Joseph M. Newcomer [MVP]
email: XXXX@XXXXX.COM
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm


Application crashes when closed

by Joseph M. Newcomer » Thu, 10 May 2007 10:06:11 GMT

Make sure that you don't have an explicit load of the CRT libraries in the linker command
line. Also, make sure that you don't have any .obj files that were compiled using the
single-threaded library, as they will force it to be loaded, causing the conflict.
joe



Joseph M. Newcomer [MVP]
email: XXXX@XXXXX.COM
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm


Application crashes when closed

by UHVuaXQgS2F1cg » Fri, 11 May 2007 00:48:02 GMT



I used WinDbg tool to find out where the problem is and it showed the
problem in myodbc3.dll, I am using MySQL database. So I commented out
everything relted to the database and it gave no problems. I also created a
new dialog based application where I just open the database in the OnInit
dialog() and close the database in OnClose().

BOOL CTryDlg::OnInitDialog()
{
CDialog::OnInitDialog();

// Add "About..." menu item to system menu.

// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);

CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}

// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
if (!TelexDB.IsOpen())
{
/********added code ***************/
try
{
TelexDB.Open( "VoiceStore",FALSE,FALSE,"ODBC;UID=root;PWD=",FALSE );
}
catch(...)
{
MessageBox("Failed To Connect To Database","Error",
MB_OK|MB_ICONINFORMATION) ;
}
}
/**************End of added code ************/

SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon

// TODO: Add extra initialization here

return TRUE; // return TRUE unless you set the focus to a control
}

void CTryDlg::OnClose()
{
// TODO: Add your message handler code here and/or call default
if (TelexDB.IsOpen())
{
TelexDB.Close();
}
CDialog::OnClose();
}


It doesnt show any compiler errors. While using WinDbg and when I close the
application it gives this error. I am guessing there is either a problem in
the way I am opening and closing the database or there is a bug in
myodbc3.dll.

Please let me know your comments.




Application crashes when closed

by Victor » Fri, 11 May 2007 03:18:06 GMT

ave you tried to
catch(CDBException*e) exception?

Victor

"Punit Kaur" < XXXX@XXXXX.COM > wrote in message
news: XXXX@XXXXX.COM ...




Similar Threads

1. On closing application ntdll.dll is crashed

2. Closing documents caused random crash in ActiveX server application

3. Closing documents caused random crash in ActiveX server application

4. how to close a form without closing application

Henry,
Do not pass an instance of a form to the Application.Run method (in your
Main routine). Instead show your form, and then call Application.Run()

When you are ready to exit the application use Application.Exit.

Hope this helps
Jay


"Henry" < XXXX@XXXXX.COM > wrote in message
news:184301c37873$c5c06b80$ XXXX@XXXXX.COM ...
> My application has a single form. When I need, I open the
> same kind of form (duplicate) from the form. If I close
> the duplicated form, then the application is keeping
> alive. OK. My problem is  that if I close the initial
> form, then all the other forms are closed and the
> application exit.
>
> How can I do so that each time I just close one window, no
> matter which window, the application still run if there is
> another window present.


5. Application closes when closing the document.

6. closing Print Preview closes application

When I click on the X from the print preview page, the entire
application gets closes.  How do I prevent this or disable the close
button?

Thanks

7. Application closes when child form is closed. - Borland C++ Builder VCL Components

8. Closing a Window from Taskbar closes the application

Hi, I am using the TTrayIcon from Borland. I found out that when I close 
a window from my application using a right on my window's taskbar 
object, it closes my whole application. I only want my application to be 
closed when I right click on the system tray icon and choose Close.

Is there a property that I have missed?

Thank you

Simon