none
dialog on cancel run time error : Run-Time Check Failure #2 - Stack around the variable xxx was corrupted. RRS feed

  • Question

  • Hi I have mfc  mdi   application;

    I have a dialog schedDlg   which  invoked from a parent window  TignSetup

    like this     :   schedDlg evtDlg(0,1);  evtDlg.domodal();

    the dialog shows up and everything is ok;

    however when I click cancel button on the dialog i get run time error:Run-Time Check Failure #2 - Stack around the variable 'evtDlg' was corrupted.

    my guessing is that    because schedDlg does not provide a desctructor   the oncancel  method fails

    but as i see it  the constructor does not allocate any memory which is needed to be released

    CScheduleEventDlg::CScheduleEventDlg(int rows, int enableServiceScroll, CWnd* pParent /*=NULL*/)
    	: CDialog(CScheduleEventDlg::IDD, pParent)
    {
    //{{AFX_DATA_INIT(CScheduleEventDlg)
    	m_currState = "";//NULL;//_T("");
    	m_effFromDay = 0;
    	m_effFromMonth = 0;
    	m_effFromYear = 0;
    	m_effToDay = 0;
    	m_effToMonth = 0;
    	m_effToYear = 0;
    	m_excFromHour = 0;
    	m_excToHour = 0;
    	m_friday = FALSE;
    	m_monday = FALSE;
    	m_saturday = FALSE;
       m_sunday = FALSE;//
    	m_thursday = FALSE;
    	m_tuesday = FALSE;
    	m_frequency = -1;
    	m_wednesday = FALSE;
    	m_intervalHour = 0;
    	m_runTimeHour = 0;
    	m_runTimeMin = 0;//
    	m_suspend = FALSE;
    	m_type = -1;
    	m_excFromMin = 0;//
    	m_excToMin = 0;
    m_intervalMin = 0;
    	//}}AFX_DATA_INIT
    m_rows = rows;
      m_enableServiceScroll = enableServiceScroll;
      m_initFromGlobalSetup = 0;
    	
    }


    I am skeptic about the first item m_currState="";    

    Any suggestions how to fix the problem will be appreciated




    • Edited by kobosh Friday, June 28, 2013 3:01 PM
    Friday, June 28, 2013 2:55 PM

Answers

  • if i call the dialog off a pointer like this

    CScheduleEventDlg    evntDlg=new 

    CScheduleEventDlg(......)

    evntDlg->doModal();

    instead of

    CScheduleEventDlg evntDlg(.......);

     the problem is solved

    • Marked as answer by kobosh Friday, August 9, 2013 8:01 PM
    Friday, August 9, 2013 8:01 PM

All replies

  • Nothing in what you have shown is likely to have caused the stack corruption.  Try showing the function that calls evtDlg.DoModal();  It is also possible that some code in CScheduleEventDlg corrupts some random memory somewhere, and that random memory happens to be on the stack where you are seeing the issue.

    Friday, June 28, 2013 3:05 PM
  • thanks simonRev;

    this is the function calling dialog

    int CTignSchListDlg::EditSchEvent( CScheduleEvent &schEvt )
    {
      int rtn = TRX_FAIL;
     int numOfThreads = 0;
    
      
      CScheduleEventDlg evtDlg(m_numOfThreads, m_enableServiceScroll);
      
    
    
      evtDlg.m_initFromGlobalSetup = m_initFromGlobalSetup;  
    
      if(!m_enableServiceScroll)
      {
        evtDlg.m_eventId = schEvt.m_eventId;
        evtDlg.m_threadId = schEvt.m_threadId;
      }
      evtDlg.SetInputVars( schEvt );
     if ( evtDlg.DoModal() == IDOK )
      {
        evtDlg.GetInputVars( schEvt );
        if(m_enableServiceScroll)
        {
          schEvt.m_threadId = evtDlg.m_threadId;
          schEvt.m_eventId  = evtDlg.m_eventId;
        }
        m_changesMade = TRUE;
        rtn = TRX_OK;
     }
      return rtn;
    }
    Even I  modify the code to look like this :
    int CTignSchListDlg::EditSchEvent( CScheduleEvent &schEvt )
    {
      int rtn = TRX_FAIL;
     int numOfThreads = 0;
    
      
      CScheduleEventDlg evtDlg(m_numOfThreads, m_enableServiceScroll);
      
    
    
      evtDlg.m_initFromGlobalSetup = m_initFromGlobalSetup;  
    
     
     evtDlg.DoModal();
      
      return rtn;
    }

     the dialog shows up normal but  error occurs on cacel


    Friday, June 28, 2013 3:33 PM
  • Try commenting out whatever code runs inside the dialog. Something in that code is probably acccessing memory that it should not be accessing. Narrow it down with commenting out of code.
    Friday, June 28, 2013 4:40 PM
  • i commented out everything before  and after calling the dialog

    In the calling window

    CScheduleEventDlg evtDlg(m_numOfThreads, m_enableServiceScroll);
      //evtDlg.m_initFromGlobalSetup = m_initFromGlobalSetup;  
      evtDlg.DoModal();

     

    and oninitdialog of the dialog

    only : CDialog::oninitdialog()

    but still get the error   when i hit cancel button


    Friday, June 28, 2013 4:57 PM
  • Are there other member functions, handlers or controls of CScheduleEventDlg that can be commented?

    Friday, June 28, 2013 6:38 PM
  • i commented out all functions except oninitdailag    oncancel and dodataexchange

    but still get error; is there a way to catch that run time error ?if i can do that then the problem is solved because when i get the error and click on continue it returns to the parent window

    Friday, June 28, 2013 7:40 PM
  • i commented out all functions except oninitdailag    oncancel and dodataexchange

    but still get error; is there a way to catch that run time error ?if i can do that then the problem is solved because when i get the error and click on continue it returns to the parent window


    Stomping a memory corruption error is rarely, if ever a good idea.  All it does is delay finding the problem until even later when it will be even harder to figure out what is going on (most likely at your customer site).
    Friday, June 28, 2013 7:43 PM
  • i did   a try /catch     at where  dialog is instantiated and called 

    try{

     ....

    evtDlg.domodal

    }catch()

     and in oncancel method

    but still get the error

    Friday, June 28, 2013 7:53 PM
  • well; I commented out all member variables except the ones I pass into the constructor; and I commented out all functions except oninitdaialog   and dodataexchange; now I get no run time error on cancelling;

    any ideas  how  add functions and variables  to detect problem area?

    Friday, June 28, 2013 11:37 PM
  • Now start uncommenting stuff a little bit at a time and see when the problem shows back up.  You can use trial and error to get it down to a single line.  If unclear as to why that line is problematic, then feel free to ask about that.
    Saturday, June 29, 2013 3:44 AM
  • the constructor is the source of problem: I added  all member variables which are initialized in the constructor and now I have the run time error

    CScheduleEventDlg::CScheduleEventDlg(int rows, int enableServiceScroll, CWnd* pParent /*=NULL*/)
    	: CDialog(CScheduleEventDlg::IDD, pParent)
     {
    //{{AFX_DATA_INIT(CScheduleEventDlg)
    	m_currState = " ";//NULL;//_T("");
    	m_effFromDay = 0;
    	m_effFromMonth = 0;
    	m_effFromYear = 0;
    	m_effToDay = 0;
    	m_effToMonth = 0;
    	m_effToYear = 0;
    	m_excFromHour = 0;
    	m_excToHour = 0;
    	m_friday = FALSE;
    	m_monday = FALSE;
    	m_saturday = FALSE;
       m_sunday = FALSE;//
    	m_thursday = FALSE;
    	m_tuesday = FALSE;
    	m_frequency = -1;
    	m_wednesday = FALSE;
    	m_intervalHour = 0;
    	m_runTimeHour = 0;
    	m_runTimeMin = 0;//
    	m_suspend = FALSE;
    	m_type = -1;
    	m_excFromMin = 0;//
    	m_excToMin = 0;
    m_intervalMin = 0;
    	//}}AFX_DATA_INIT
    m_rows = rows;
     m_enableServiceScroll = enableServiceScroll;
      m_initFromGlobalSetup = 0;
     
    	
    }

     But I suspect the problem  is carry over from Parent window, what do you think? this is because the try \catch did not work

    Saturday, June 29, 2013 12:34 PM
  • Sorry; the problem may be caused by initialization of variables in the constructor ; one or more of these

    //{{AFX_DATA_INIT(CScheduleEventDlg)
    /*m_currState = " ";//NULL;//_T("");
    m_effFromDay = 0;
    m_effFromMonth = 0;
    m_effFromYear = 0;
    m_effToDay = 0;
    m_effToMonth = 0;
    m_effToYear = 0;
    m_excFromHour = 0;
    m_excToHour = 0;
    m_friday = FALSE;
    m_monday = FALSE;
    m_saturday = FALSE;
       m_sunday = FALSE;//
    m_thursday = FALSE;
    m_tuesday = FALSE;
    m_frequency = -1;
    m_wednesday = FALSE;
    m_intervalHour = 0;
    m_runTimeHour = 0;
    m_runTimeMin = 0;//
    m_suspend = FALSE;
    m_type = -1;
    m_excFromMin = 0;//
    m_excToMin = 0;
    m_intervalMin = 0;*/
    //}}AFX_DATA_INIT

    Saturday, June 29, 2013 12:52 PM
  • I narrowed it down to the last two

    // m_excToMin = 0;
    //m_intervalMin = 0;

    either of them will cause the error

    Saturday, June 29, 2013 1:14 PM
  • I narrowed it down to the last two

    // m_excToMin = 0;
    //m_intervalMin = 0;

    either of them will cause the error

    I doubt that they are the direct cause. Try the assignments in a different order and see
    which ones then *appear* to "cause" the error. For example, make those two the *first*
    two rather than the last two.

    - Wayne

    Saturday, June 29, 2013 1:40 PM
  • Now I have commented out the last two variables initialization in constructor   , this part of code works fine

    CScheduleEventDlg evtDlg(m_numOfThreads, m_enableServiceScroll);
      evtDlg.m_initFromGlobalSetup = m_initFromGlobalSetup;  

    until i get to here
      evtDlg.DoModal();

    then I get : access violation error   ;  

    Saturday, June 29, 2013 1:56 PM
  • Have you tried running a static analysis of your code? e.g. -

    Cppcheck
    http://cppcheck.sourceforge.net/

    PC-lint
    http://www.gimpel-online.com/OnlineTesting.html

    - Wayne
    Saturday, June 29, 2013 1:57 PM
  • I doubt you are even looking in the right place for your error. The problem with memory corruption bugs is that the program doesn't die immediately but continues to run for a period of time until the corrupted memory is accessed, and then the access violation is triggered, but in some innocent code area. I suspect your bug is found in code that has executed some time before evtDlg is used.

    My personal opinion is that a good code review, preferably with eyes other than your own, tends to be the most fruitful approach (and may uncover other unrelated problems to boot). Some material listed below may provide some help. If you come across other articles that are useful, I'd really like to hear from you so I can add it to my list.

    Native Code: Heap Corruption/Memory Leaks
    Enable the Page Heap
    How to use the PageHeap utility to detect memory errors in a Microsoft Visual C++ project
    How to use Pageheap.exe in Windows XP, Windows 2000, and Windows Server 2003
    Using Application Verifier to Troubleshoot Programs in Windows XP
    It is recommended to replace all occurrences of the unsafe buffer-copy APIs such as strcat, strcpy, or wcscpy with the secure ones like StringCchCopy, strcpy_s, and wcscpy_s, _mbscpy_s. You can use PREFast to find all unsafe uses of buffer-copy APIs, and replace them one by one.
    Memory Leak Detection Enabling
    Heap State Reporting Functions
    How can I Debug an Access Violation?
    Debugging Heap Corruption in Visual C++ Using Microsoft Debugging Tools For Windows
    Avoiding Buffer Overruns
    Debug Tutorial Part 3: The Heap
    Saturday, June 29, 2013 3:58 PM
  • thanks Brian ; the cause is at  this function ; if this function is commented out the error goes away

    void SchSplitTime( long timeNum, short &hour, short &minute )
    {
      hour = (short) ( timeNum / SECS_PER_HOUR );
      minute = (short) ( ( timeNum % SECS_PER_HOUR ) / SECS_PER_MIN );
    }

    and this function is called at 

    void CScheduleEventDlg::SetInputVars( CScheduleEvent &schEvt ) { .........

    .....

    ........... short m, d, y, min; long startDate = schEvt.m_startDate == 0 ? time( NULL ) : schEvt.m_startDate; SplitTime( startDate, m_effFromMonth, m_effFromDay, m_effFromYear, y, min ); if ( schEvt.m_endDate == 0 ) m_effToMonth = m_effToDay = m_effToYear = 0; else SplitTime( schEvt.m_endDate, m_effToMonth, m_effToDay, m_effToYear, y, min ); switch ( schEvt.m_type ) { case SCH_RUN_EVENT: if ( schEvt.m_interval != 0 ) SchSplitTime( schEvt.m_interval, m_intervalHour, m_intervalMin ); else { m_intervalHour = 1; m_intervalMin = 0; }


    class CScheduleEvent
    {
    public :
      CScheduleEvent();
      void Reset();
    
      // attributes
      short m_eventId;
      short m_threadId;
      short m_type;
      short m_state;
      short m_frequency;
      char m_days;
      char m_suspended;
      long m_startDate;
      long m_endDate;
      union
      {
        struct
        {
          long m_runTime;
          long m_interval;
        };
        struct
        {
          long m_excludeStartTime;
          long m_excludeEndTime;
        };
      };
    };

    i dont know what is wrong with it?

    Sunday, June 30, 2013 12:24 AM
  • Your practice of commenting out parts of code and then concluding that this part is
    the cause of the error if the error "goes away" is flawed. Whenever you make changes
    to code such as removing parts of it then you alter the "footprint" of the object
    code. The layout of the exe in memory will be different each time you make such
    a change. As a result, any errant pointers or buffer overruns, etc. may affect
    a different part of the program since the location of any overruns or overwrites
    of heap, stack or code will corrupt something different. This will result in
    different *symptoms*.

    You need to focus on finding all possible cases of invalid pointer use, buffer
    overruns, etc. Static analysis can help in this task.

    - Wayne
    Sunday, June 30, 2013 1:39 AM
  • thanks Wayne; but what you say is bigger than me

    so what is static analysis and how can i do it

    Sunday, June 30, 2013 2:09 AM
  • this is the only place where i can see a pointer used

     CScheduleEvent *evt = (CScheduleEvent *) m_eventList.GetItemData( sel );
        m_threadId = evt->m_threadId;
        if ( EditSchEvent( *evt ) && SetColumns( sel, evt ) )

    and  the function   EditSchEvent( *evt ) is the one that calls   

    SchSplitTime( schEvt.m_interval, m_intervalHour, m_intervalMin ); which is said is causing the error

    perhaps the pointer should be deleted after function execution?

    Sunday, June 30, 2013 2:36 AM
  • so what is static analysis and how can i do it


    I gave you two links already. One is free and the other is a test drive.

    - Wayne

    Sunday, June 30, 2013 2:37 AM
  • Try watching the data around the variable evtDlg. Add this line after the definition of evtDlg:

    BYTE * p = (BYTE*)(&evtDlg + 1);

    Put a breakpoint then watch this location in a Memory window of debugger, executing the code step-by-step.

    The debugger is able to watch modifications automatically. Stop at the first line after the variable evtDlg, then go to DEBUG à Windows à Breakpoints and add a “New data breakpoint”. Specify the ‘&evtDlg + 1’ address and ‘1’ byte count.


    • Edited by Viorel_MVP Sunday, June 30, 2013 7:55 AM ____
    Sunday, June 30, 2013 7:52 AM
  • thanks the value of P was 204 'I' I am not sure of the last character 'I'
    Sunday, June 30, 2013 1:47 PM
  • this is the only place where i can see a pointer used

     CScheduleEvent *evt = (CScheduleEvent *) m_eventList.GetItemData( sel );
        m_threadId = evt->m_threadId;
        if ( EditSchEvent( *evt ) && SetColumns( sel, evt ) )

    Do you really mean to tell us that there aren't *any* other pointers *anywhere* in the
    entire program? If you are still focusing all of your bug searching on just the area
    of the code where the errors are *manifested*, then you have failed to grasp what Brian
    and I have been telling you. Bugs such as pointer misuse or buffer overruns can occur
    *anywhere* in the program, but the effect may not be observed until much later in some
    other  - probably unrelated - part of the program. That's the nature of random corruption.

    In addition to invalid pointer values being used, and buffer overruns causing corruption,
    other common causes of such symptoms include: deleting a pointer to allocated heap memory
    which has already been deleted (corrupts the heap); deleting a pointer which was not set
    via new/new[].

    - Wayne

    Sunday, June 30, 2013 7:59 PM
  • thanks Wayne again; I installed Application Verifier    used the default tests configuration : heap , memory ...ETC

    add my application and then ran the program and nothing showed up in logs; 

        
    Sunday, June 30, 2013 11:01 PM
  • I installed Application Verifier    used the default tests configuration : heap , memory ...ETC

    add my application and then ran the program and nothing showed up in logs; 

        

    So I guess there's nothing wrong with your application then and you can just ignore the run
    time errors you've been seeing.

    Seriously, do you think that a test with one diagnostic tool designed to catch a specific
    set of issues is sufficient to detect all problems? Further, do you think that Application
    Verifier will help you find exactly where in your *source* code there are problems?

    Try an obvious bug such as this and see if Application Verifier will show anything in its logs:

    char a[10] = {};
    a[10] = 'X';

    Why do you refuse to try a static analyzer?

    - Wayne

    Monday, July 1, 2013 12:53 AM
  • which one of the links is static analysis
    Monday, July 1, 2013 2:18 AM
  • Hi Wyne

    I tried cppcheck       the GUI is stupid and you cannot check  a folder or a solution; it will say "xxxx" is already there do you want to replace it?

    i tried command line it works with a whole folder but almost checks nothing the only error i saw was in one cpp file : xx not initiallized  and this error repeated ... the rest was like  xxx.cpp completed x%.....

    now can you look into 

    class CScheduleEvent
    {
    public :
      CScheduleEvent();
      void Reset();
    
      // attributes
      short m_eventId;
      short m_threadId;
      short m_type;
      short m_state;
      short m_frequency;
      char m_days;
      char m_suspended;
      long m_startDate;
      long m_endDate;
      union
      {
        struct
        {
          long m_runTime;
          long m_interval;
        };
        struct
        {
          long m_excludeStartTime;
          long m_excludeEndTime;
        };
      };
    };
    
    ////////
    int rtn = TRX_FAIL; // Failure
      int loop = 1;
      int id = 0, oldId = 0, i = 0; 
      char type[_MAX_DIR];// length is 256
      char value[_MAX_DIR];
    
      memset(type,        0,  sizeof(type));
      memset(value,       0,  sizeof(value)); 
    
      rtn = GetNumOfEvents(db, threadTitle);
      if (rtn == TRX_OK && (m_numOfEvents!=0))
      {
        m_events = new CScheduleEvent[m_numOfEvents];
        if (!m_events)
        {
          m_numOfEvents = 0;
          ErrorMessage( "LoadScheduleData: Failed to allocate memory for events.");
        }
        else
        {
          if (db.GetNewDBProc() == 0)
    		    Log( "Error: Could not create a new dblib process."), rtn = TRX_FAIL;
    	    else
    	    {
            if (db.ExecFCmd(	
    
    			      " SELECT	Type,   "
    			      "			    Value,  "
                "         ID      "
    			      " FROM ProvSvrSettings "
    			      " WHERE Owner = '%s' "
                " AND Class = 'Schedule' "
                " AND Application = 'ProvSvr' ",
    			      threadTitle))
    	      {
    		      db.Bind(type,			    sizeof(type),			  STRINGBIND);
    		      db.Bind(value,		    sizeof(value),		  STRINGBIND);
              db.Bind(&id,          sizeof(id),         INTBIND);
    
              while (loop)
              {
                oldId = id;
                switch(db.NextRow())
    			      {
    			       case REG_ROW:
    
                   Rtrim(type);
                   Rtrim(value);
               
                   if (oldId != id && oldId != 0)
                     i++;
                   
                   m_events[i].m_eventId = i;
                   if (strncmp(type,  "Type",  strlen(type)) == 0)
                     m_events[i].m_type = atoi(value);
                   else if (strncmp(type,  "State",  strlen(type)) == 0)
                     m_events[i].m_state = atoi(value);
                   else if (strncmp(type, "Frequency",  strlen(type)) == 0)
                     m_events[i].m_frequency = atoi(value);
                   else if (strncmp(type, "Days",  strlen(type)) == 0)
                     m_events[i].m_days = value[0];
                   else if (strncmp(type, "Suspended",  strlen(type)) == 0)
                     m_events[i].m_suspended = value[0];
                   else if (strncmp(type, "StartDate",  strlen(type)) == 0)
                     m_events[i].m_startDate = atol(value);
                   else if (strncmp(type, "EndDate",  strlen(type)) == 0)
                     m_events[i].m_endDate = atol(value);
                   else if (strncmp(type, "RunTime",  strlen(type)) == 0)
                     m_events[i].m_runTime = atol(value);
                   else if (strncmp(type, "Interval",  strlen(type)) == 0)
                     m_events[i].m_interval = atol(value);
                   else if (strncmp(type, "ExcludeStartTime",  strlen(type)) == 0)
                     m_events[i].m_excludeStartTime = atol(value);
                   else if (strncmp(type, "ExcludeEndTime",  strlen(type)) == 0)
                     m_events[i].m_excludeEndTime = atol(value);
                   break;
    
    			       case NO_MORE_ROWS:
    
                   loop = 0;
                   break;
                }
              }
            }
            db.ReleaseDBProc();
          }
        }
      }
    
      return rtn;
    }

    m_Events is array of CSheduleEvent objects  

    class CScheduleEvent
    {
    public :
      CScheduleEvent();
      void Reset();
    
      // attributes
      short m_eventId;
      short m_threadId;
      short m_type;
      short m_state;
      short m_frequency;
      char m_days;
      char m_suspended;
      long m_startDate;
      long m_endDate;
      union
      {
        struct
        {
          long m_runTime;
          long m_interval;
        };
        struct
        {
          long m_excludeStartTime;
          long m_excludeEndTime;
        };
      };
    };
    



    Monday, July 1, 2013 1:58 PM
  • Where is this variable 'evtDlg' declared?

    Just a thought...

    A good example of this error is when you use the fscanf function. You are trying to read in a char variable and for that you give a format specifier for unsigned short. This will result in fscanf writing over the next variable as char is just one byte and then the compiler (for debug builds) check you specified kicks in to help you saying that 'stack around the variable is corrupt'. I guess the error message will name the variable following the one given in fscanf. 


    Blog: http://ntcoder.com/bab


    Posts are provided as is without warranties or guaranties.

    Monday, July 1, 2013 2:27 PM
    Moderator
  • thanks you may be right because the variable  (m_intervalMin)  that  I suspect causing this error is of type short

    a function tries to copy a  variable of type short to this variable

     SchSplitTime( schEvt.m_interval, m_intervalHour, m_intervalMin );

    here m_intervalMin is passed by ref       

    Monday, July 1, 2013 3:07 PM
  • I am trying to use cppcheck  in command line and go over .cpp classes one by one

    so far I get

    Cppcheck> cppcheck   C:\.....\xx.cpp

    checking : C:\.........xx.cpp : _DEBUG    

    I assume xx.cpp is good to go?

    Monday, July 1, 2013 3:14 PM
  • i ran cppcheck on Stringfunctons.cpp

    i got this error:  mismathc allocation and deallocation :tmpStr

    and here is the function 

    char *Clean( char *str)
    {
    	if (str)
    	{
    		LRtrim(str);
    
    		char *tmpStr = new char[strlen(str)+1];
    		
    		if (tmpStr)
    		{
    			memset( tmpStr, 0, strlen(str)+1);
    
    			char *tmpPtr = tmpStr;
    			for (char *ptr = str; *ptr != 0; ptr++)
    			{
    				// Replace tabs with spaces.
    				if (*ptr == '\t')
    					*ptr = ' ';
    
    				// If the current character is a space and the 
    				// previous one also, then ingore the current one.
    				// Otherwise, copy it.
    				if (!(*ptr == ' ' && *(ptr-1) == ' '))
    				{
    					*tmpPtr = *ptr;
    					tmpPtr++;
    				}
    			}
    			// Copy clean string back.
    			strncpy( str, tmpStr, strlen(str));
    			if (tmpStr)	delete tmpStr, tmpStr = 0;
    		}
    	}
    	return str;
    }
     but this function is never used in my application; also what is wrong with deallocation

    Monday, July 1, 2013 3:32 PM
  • While I suspect that it is not your problem, you allocate tmpStr with the array version of new and delete it with the non-array version which is undefined behavior.

    You need to use delete[].

    Also, since new throws on failure, there is no reason to check the return value of new.

    Monday, July 1, 2013 4:16 PM
  • thanks for following through; i will make the correction and see;


    Monday, July 1, 2013 5:39 PM
  • #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h>

    _CrtDumpMemoryLeaks();

    i tried this but did not work;

    do you have example i can follow?

    Monday, July 1, 2013 9:11 PM
  • Hi every body; i found  this in code project for detection of memory leaks using c++ tools ;

    can any one read the gibberish in the  debug output window and tell me?

    'MemoryTestApp.exe': Loaded 'C:\Users\hmohamed\Downloads\MemoryTestApp\MemoryTestApp\MemoryTestApp\debug\MemoryTestApp.exe', Symbols loaded.
    'MemoryTestApp.exe': Loaded 'C:\Windows\SysWOW64\ntdll.dll', Cannot find or open the PDB file
    'MemoryTestApp.exe': Loaded 'C:\Windows\SysWOW64\kernel32.dll', Cannot find or open the PDB file
    'MemoryTestApp.exe': Loaded 'C:\Windows\SysWOW64\KernelBase.dll', Cannot find or open the PDB file
    'MemoryTestApp.exe': Loaded 'C:\Windows\SysWOW64\msvcp100d.dll', Cannot find or open the PDB file
    'MemoryTestApp.exe': Loaded 'C:\Windows\SysWOW64\msvcr100d.dll', Cannot find or open the PDB file
    Detected memory leaks!
    Dumping objects ->
    c:\users\hmohamed\downloads\memorytestapp\memorytestapp\memorytestapp\memorytestapp\memorytestapp.cpp(56) : {239} client block at 0x00347610, subtype 0, 4 bytes long.
     Data: <    > CD CD CD CD 
    c:\users\hmohamed\downloads\memorytestapp\memorytestapp\memorytestapp\memorytestapp\memorytestapp.cpp(15) : {237} client block at 0x00347580, subtype 0, 20 bytes long.
     Data: <CodeProject.com > 43 6F 64 65 50 72 6F 6A 65 63 74 2E 63 6F 6D 00 
    c:\users\hmohamed\downloads\memorytestapp\memorytestapp\memorytestapp\memorytestapp\memorytestapp.cpp(41) : {173} client block at 0x003474A0, subtype 0, 80 bytes long.
     Data: <                > 01 00 00 00 03 00 00 00 05 00 00 00 07 00 00 00 
    Object dump complete.
    The program '[6836] MemoryTestApp.exe: Native' has exited with code 0 (0x0).
    
    
    
    
    
    
    
    http://www.codeproject.com/Articles/66324/Detecting-Memory-Leaks-using-the-CrtDbg-Library
    
    #include "stdafx.h"
    #include "crtdbg.h"
    
    #include <iostream>
    using namespace std;
    
    #define  new new(_CLIENT_BLOCK,__FILE__, __LINE__)
    
    void Show()
    {
       cout<<"Inside Show function\n";
       char *test = new char[20]; // No Delete called for this allocated memory so this application is having memory leak.
       strcpy_s(test, strlen(test),"CodeProject.com");
       cout<<test<<"\n";
    
       
    }
    
    class Sample
    {
    public:
       Sample()
       {
       }
       ~Sample() { }
       void SampleShow()
       {
          cout<<"We are inside Sample Show\n";
       }
    private:
       int a;
    
    };
    int _tmain(int argc, _TCHAR* argv[])
    {
       _CrtMemState s1,s2,s3;
    
       _CrtMemCheckpoint(&s1);// Memory snapshot will be taken at this point
    
       int *number = new int[20]; // No Delete called for this allocated memory so this application is having memory leak.
    
       for( int i =0; i<20; i++)
       {
          number[i] = i*2+1;
       }
       for( int i= 0; i<20; i++)
       {
          cout<<"Number["<<i<<"] : "<<number[i]<<"\n";
       }
    
       Show();
       int test;
       Sample *obj = new Sample();
       obj->SampleShow();
       Sample *obj1 = new Sample(); //No Delete called for this allocated memory so this application is having memory leak.
       obj1 = obj;
       obj1->SampleShow();
       delete obj;
         delete obj1; 
       _CrtMemCheckpoint(&s2);// Another Memory snapshot will be taken at this point
    
       if(_CrtMemDifference(&s3,&s2,&s1)) // Memory difference which has been allocated but deallocted between s1 and s2 
                                          // Memory check points will be calculated. 
       {
          _CrtDumpMemoryLeaks();  //Dumps the memory leak in Debugger Window, if any, between s1 and s2 memeory check points.
       }
       
       return 0;
    }
    
    

    Monday, July 1, 2013 11:37 PM
  • if i call the dialog off a pointer like this

    CScheduleEventDlg    evntDlg=new 

    CScheduleEventDlg(......)

    evntDlg->doModal();

    instead of

    CScheduleEventDlg evntDlg(.......);

     the problem is solved

    • Marked as answer by kobosh Friday, August 9, 2013 8:01 PM
    Friday, August 9, 2013 8:01 PM