Re: Access violation on calling GetSafeHwnd()
On Fri, 02 Mar 2007 00:42:36 -0500, Joseph M. Newcomer
<newcomer@flounder.com> wrote:
One of the situations I've seen that causes a failure is when there is a CWnd * that is a
local or member variable that is uninitialized, so it is something like 0xcccccccc or
0xcdcdcdcd. Of course, if he had gone into the debugger and examined the variable and
reported it, perhaps there would be a chance to figure out what had gone wrong.
joe
Unless I'm missing something, his code involves a "this" pointer becoming
corrupted inside a member function. He had:
BOOL CZedObjectFrame::OnCmdMsg( UINT nID, int nCode, void * pExtra,
AFX_CMDHANDLERINFO* pHandlerInfo)
<snip>
rc = CFrameWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
access violation here >>>> HWND viewHandle = GetSafeHwnd();
Apparently, the OnCmdMsg upcall to the base class went all right, but upon
return, he GPF's when he calls GetSafeHwnd, which as I noted, could hardly
be simpler (below I changed m_hWnd to this->m_hWnd to emphasize the
implicit dereference):
HWND viewHandle = (this != 0) ? this->m_hWnd : 0;
The "this" pointer is typically kept in a register and is passed in a
register to normal member functions, which follow the __thiscall calling
convention. So how can it get corrupted? I can think of three
possibilities:
1. The base class OnCmdMsg didn't preserve the register
CZedObjectFrame::OnCmdMsg was using to hold "this", or
2. CZedObjectFrame::OnCmdMsg had to dump "this" to the stack, and upon
return from CFrameWnd::OnCmdMsg, it loaded a bad pointer due to stack
corruption, or
3. The memory holding the CZedObjectFrame object was decommitted. (If it
weren't decommitted, he'd load a garbage HWND value and fail later.)
Only (2) seems even somewhat likely. Oh well, enough guessing. I'd actually
be surprised if any of it applies. :)
--
Doug Harrison
Visual C++ MVP