Debugging using the Call Stack


Click here to change the theme.

First, I will assume you are executing your program using the debugger. If you encounter an exception or assertion during debugging the call stack can be very helpful.

The Call Stack is where computers store stuff when functions are called. It is how the computer knows where to return to and such (that is quite a simplified view but it gives an idea of what the stack is).

When you get an assertion, look at the call stack. You might need to display the window for the call stack. Each line (row) of the call stack is a function call. The top line will be the last location executed before the debugger got control. In the case of an assertion, it will be the MFC source code line containing the assertion. There is usually a comment giving some idea of the problem. You can also double-click on other lines to see where the function call was made from that took execution to the function above it. If you find the last function call (the top-most line) in the call stack that shows a function call from your program, then that is where in your source code that the MFC code was called from that the assertion was encountered. Sometimes the problem is obvious and sometimes it is not, but at least this will likely give a much more specific indication of the problem.

See Sample Call Stack for a sample I created by putting a flaw into one of my programs. Only the top three lines are significant. Normally the call stack window is kept small enough to show just the top few lines.

The top line in the call stack says:

CListCtrl::InsertColumn(int 0, const tagLVCOLUMNA * 0x0012ef98) line 176 + 46 bytes

By double-clicking on the line we are taken to the corresponding source code line:

_AFXCMN_INLINE int CListCtrl::InsertColumn(int nCol, const LV_COLUMN* pColumn)
    { ASSERT(::IsWindow(m_hWnd)); return (int) ::SendMessage(m_hWnd, LVM_INSERTCOLUMN, nCol, (LPARAM)pColumn); }

The relevant part is the part that says:

ASSERT(::IsWindow(m_hWnd));

When I click on the line that says:

CDataSourcesDlg::OnInitDialog() line 57

I see the part of my program that has:

m_DataSourcesList.InsertColumn(0, "Name");
m_DataSourcesList.InsertColumn(1, "Description");

So in this case, the problem is that the list control is not yet created. The "IsWindow(m_hWnd)" is not true because  the window has not been created.