+ 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
    Posts
    49
    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.

    Code:
    class CMyString
    {
    private:
    	char* m_pData ;
    	CMyString(const CMyString&) ;//do not allow copy
    	CMyString& operator =(const CMyString&) ;//do not allow assignment
    public:
    	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) ;
    		}
    	}
    
    	~CMyString()
    	{
    		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") ;
    
    	if(true)
    	{
    		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()
    {
    	try
    	{
    		ICauseACrash() ;
    	}
    	catch(int n)
    	{
    		OutputDebugString("caught an exception...\n") ;
    	}
    }
    Thanks.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

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