+ Reply to Thread
Results 1 to 2 of 2

Thread: What is stack unwinding?

  1. #1

    What is stack unwinding?

    What is stack unwinding? How can we simulate it?

    Any example would help a lot in C++.

  2. #2
    Junior Member
    Join Date
    Feb 2012
    Stack unwinding is the useful when there is any exception is thrown and you want to know how objects on the stacks are destroyed.

    If you have raw pointers allocated and exception is thrown in the same context then it is quite possible that you may leak memory.

    Below example depicts that pIAmAboutToBeAbandoned leaks the memory.

    While another object objMyString does not leak the memory even if it allocates the memory using 'new' keyword!
    Its destructor will get executed once objMyString object gets out of the scope and it will destroy the object using 'delete'!

    So always use the high level object (like MyString here, or std::string) instead of 'char *' whenever possible.

    class CMyString
    	char* m_pData ;
    	CMyString(const CMyString&) ;//do not allow copy
    	CMyString& operator =(const CMyString&) ;//do not allow assignment
    	CMyString(char* pData)
    		if(NULL != pData)
    			OutputDebugString("memory is allocated for CMyString::char...\n") ;
    			m_pData = new char[strlen(pData) + 1] ;
    			strcpy(m_pData, pData) ;
    		if(NULL != m_pData)
    			OutputDebugString("memory is freed for CMyString::char...\n") ;
    			delete m_pData ;
    			m_pData = NULL ;
    } ;
    void ICauseACrash()
    	char *pIAmAboutToBeAbandoned = new char[1000] ;
    	OutputDebugString("memory is allocated for char...\n") ;
    	CMyString objMyString("Hello World to Stack unwinding!\n") ;
    		OutputDebugString("throwing an exception...\n") ;
    		throw 1 ;
    	//this will never be caught as we are throwing an exception above in every case.
    	//hence, memory leaks!
    	OutputDebugString("memory is freed for char...\n") ;
    	delete pIAmAboutToBeAbandoned ;
    	pIAmAboutToBeAbandoned = NULL ;
    void StackUnwinding()
    		ICauseACrash() ;
    	catch(int n)
    		OutputDebugString("caught an exception...\n") ;

+ Reply to Thread

Tags for this Thread


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts