Unitialized Class Calling Function, No exception. What is going on here? - c++

Is this normal behavior; this never happened to me before. I assume it would cause an exception but why doesn't it here? Take a look.
CWindowsApplication::MsgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static CWindowApplication* pApp = NULL;
if (message == WM_NCCREATE)
{
//// retrieve Window instance from window creation data and associate
//pApp = reinterpret_cast(((LPCREATESTRUCT)lParam)->lpCreateParams);
//::SetWindowLong(hWnd, GWL_USERDATA, reinterpret_cast(pApp));
//pApp = reinterpret_cast(::GetWindowLong(hWnd, GWL_USERDATA));
}
pApp->WndProc(hWnd, message, wParam, lParam); // pApp = NULL, but it still works? I expected a exception of some sort.
}
But, when I change the class to something else I get the exception I was expecting.
What is going on here? Never in my 10+ years as an enthusiastic programmer have I ever came across something like this.

As long as WndProc is not virtual, the pointer technically doesn't need to be dereferenced at all in order to make the call. That's not to say it won't crash and burn when you try to use this (including calling any virtual function with an implicit this) inside WndProc, but non-virtual calls go by the type of the pointer, and don't need to touch the vtable (or any other instance member).

All you're doing is invoking undefined behaviour. That means that it can appear to work, it can crash, or whatever the compiler feels like making it do.

Related

How does one move a std::unique_ptr between windows without risking a memory leak?

I want to do this project in C++ and be done with it once and for all:
select a movie from a list in one window and display the movie's details in another window.
I'd already arrived at Remy Lebeau's solution here and found his post because I'd realized the same limitation he did: it exposes the raw pointer to memory leakage.
(Please excuse my coding style).
MoviesWindow::MovieSelected( const unsigned int uint__MovieKey )
{ ...
std::unique_ptr<MovieBean> uptr__MovieBean = std::make_unique...
...
uptr__MovieBean->SetMovieTitle( row["MovieTitle"] );
uptr__MovieBean->SetYearReleased( row["YearReleased"] );
...
SendMessage( hwnd__MovieWindow, UWM_SendMovieBean, 0, (LPARAM) uptr__MovieBean->get() );
...
}
Fortunately, I have an advantage with SendMessage(): it won't end (releasing the std::unique_ptr) until the message handler returns, and the message handler's job is to clone the MovieBean.
MovieWindow::HandleUwmSendMovieBean( const HWND hwnd__MovieWindow, const UINT uint__WindowMessage, const WPARAM wParam, const LPARAM lParam )
{ UPTR__MovieBean = std::move( (*((MovieBean*) lParam).Clone() );
...
}
It seems the right way to do it is leave ownership of the std::unique_ptr with MovieSelected() until the actual moment of transfer by sending a reference to the handler, and using std::move on the reference.
MoviesWindow::MovieSelected( const unsigned int uint__MovieKey )
{ ...
SendMessage( hwnd__MovieWindow, UWM_SendMovieBean, 0, (LPARAM) &uptr__MovieBean );
...
}
But I cannot figure out how to get the reference out of lParam and into std::move. This would seem to be the one, but nope.
MovieWindow::HandleUwmSendMovieBean( const HWND hwnd__MovieWindow, const UINT uint__WindowMessage, const WPARAM wParam, const LPARAM lParam )
{ UPTR__NewMovieBean = std::move( reinterpret_cast<std::unique_ptr<MovieBean>*>( lParam ) );
...
}
I've tried every combination I can think of and ensured that the address sent is the address received and supplied to std::move. All I get are constant compiler errors (including a now-much-hated one about std::remove_reference), and crashes. Any insight would be appreciated.
SendMessage and unique_ptr are definitely not made for each other. I can give lots of hints here, but the best thing to do is to not be smuggling smart pointers through HWND messages.
I don't know what a UWM_SendMovieBean, but I'm guessing that's a custom windows message you either based of off WM_USER or RegisterWindowsMessage. So what you are really doing sounds like you are trying to signal another code component with SendMessage instead of a formal contract between the backing classes of both windows. It's not the worst thing ever to do this, but with a class as specialized as unique_ptr, it gets much harder to pull off.
The cheap and easy thing to do would be to have both windows share the row data structure that you have. Then your send message simply sends the uint__MovieKey as the WPARAM or LPARAM of your custom message.
But if you were on my team, and we were building this app together, I'd give you the crash course in Model-View-Presenter (and other MVC designs) that make these types of feature designs more maintainable.
I got the answer in two more tries:
MovieWindow::HandleUwmSendMovieBean( const HWND hwnd__MovieWindow, const UINT uint__WindowMessage, const WPARAM wParam, const LPARAM lParam )
{ UPTR__NewMovieBean = std::move( *((std::unique_ptr<MovieBean>*) lParam) );
...
}
Basically, sending the address of the std::unique_ptr<MovieBean> meant I was sending a pointer, so I needed to std::move(...) what the pointer was pointing to. It works fine.
This still seems sound to me: I'm leaving the MovieBean protected by a smart pointer while it's "in flight". It's effectively just a pass-by-reference that doesn't violate C++ Core Rule 33: Take a unique_ptr<widget>& parameter to express that a function reseats the widget.
The substantial problem in this usage is that my message handler is also the signal to read the MovieBean's copious information into the various CommonControls of the MovieWindow. Message handlers are supposed to be quick. The better approach is what #selbie suggested: the formal contract between the backing classes.

Pointer Not Pointing Correctly?

I am running this code in a thread, assuming receivedPosts and td->window are valid:
std::vector<Post> *receivedPosts_n = new std::vector<Post>;
*receivedPosts_n = receivedPosts;
SendMessage(td->window, WM_TIMER, IDT_TIMER_FIND_NEW_POSTS_CALLBACK,
(LPARAM) receivedPosts_n);
I'm running this code at IDT_TIMER_FIND_NEW_POSTS_CALLBACK (hwnd is td->window):
case IDT_TIMER_FIND_NEW_POSTS_CALLBACK:
{
std::vector<Post> *currentPosts_ptr = (std::vector<Post> *)lParam;
//This vector turns up as undefined
std::vector<Post> currentPosts = *currentPosts_ptr;
}
break;
But the problem is that *currentPosts_ptr turns up as an invalid pointer, i.e. it points to random memory.
What is wrong with the pointer?
Thanks.
MSDN documentation says that for WM_TIMER message value of lParam is
A pointer to an application-defined callback function that was passed to the SetTimer function when the timer was installed.
If you need to send custom messages it is much better idea just to use WM_USER through 0x7FFF that were specially designed for this scenario.

Send Cstring using and get answer using Win Message

I need to send string using win message and get back answer. Does following method has memory management problems regarding CString?
Call:
CString params = "Hello";
SendMessage(hWnd,WM_AUT_MESSAGE, (WPARAM)&params,0);
Answer:
LRESULT CMainWindow::OnMessageAuthorise(WPARAM wParam, LPARAM lParam)
{
CString *pStr = (CString*)wParam;
*pStr="Bye";
return 0;
}
It looks OK. SendMessage blocks and does not return until OnMessageAuthorise returns, so even with a pointer to a stack variable there is no race condition. (Assuming, of course, that all of this happens within the same process.)

Variable keeps getting set to NULL after function in DLL

I need valid data to be in the global variable QObject *p. However, assigning anything to this variable inside of a function works within the scope of the function, but after the function returns, p is set back to NULL, even though p is global. Here is my code:
#include ... // various includes
// p is NULL
QObject *p;
HHOOK hhk;
BOOL WINAPI DllMain(__in HINSTANCE hinstDLL, __in DWORD fdwReason, __in LPVOID lpvReserved)
{
return TRUE;
}
LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
MOUSEHOOKSTRUCT *mouseInfo = (MOUSEHOOKSTRUCT*)lParam;
QMouseEvent::Type type;
QPoint pos = QPoint(mouseInfo->pt.x, mouseInfo->pt.y);
Qt::MouseButton bu;
Qt::MouseButtons bus;
Qt::KeyboardModifiers md = Qt::NoModifier;
... // very large switch statement
// here is where i need some valid data in p
QCoreApplication::postEvent(p, new QMouseEvent(type, pos, bu, bus, md));
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
// note: MOUSEHOOKSHARED_EXPORT is the same as __declspec(dllexport)
// this function is called by the application that loads the dll
extern "C" MOUSEHOOKSHARED_EXPORT void install(QObject *mParent, DWORD threadID, HINSTANCE hInst)
{
p = mParent; // p is assigned here and keeps the value of mParent untill the function returns
hhk = SetWindowsHookEx(WH_MOUSE, MouseProc, hInst, threadID);
} // after this function returns, p is NULL
extern "C" MOUSEHOOKSHARED_EXPORT void uninstall()
{
UnhookWindowsHookEx(hhk);
}
I have tried various data structure "workarounds" such as using struct typedef etc... i can't seem to get this to work. All i need is for p to retain the value of mParent.
EDIT:
Here is where i execute install()
// EarthWidget is a class that is derived from QWidget(which is derived from QObject)
void EarthWidget::LoadAll()
{
HINSTANCE DLLinst = LoadLibrary("MouseHook.dll");
... // get functions in DLL using GetProcAddress & typedefs, etc...
// i pass in 'this' as mParent
install(this, GetWindowThreadProcessId((HWND)earthplugin->GetRenderHwnd(), NULL), DLLinst);
// note that GetWindowThreadProcessId does work and does return a valid thread id, so no problem there
}
EDIT:
Found out what was wrong. The this pointer becomes out of scope when install is executed, therefore mParent, being a QObject, initializes itself to NULL. Thus p becomes NULL. this comes back into scope when install returns, however, at a completely different memory address. The solution, after extensive debugging and headaches, would be to create a class member function that takes a QObject as a parameter and passes that into install instead of this. Whatever you pass into that function must last as long as you need the DLL to last. That, or, you can create your own copy constructor that performs a deep copy.
Are you exporting the global in the DLL and then importing it in the program? If you are not, or not doing it correctly, you probably have two p objects: one in the DLL and one in the program. You can confirm this by checking the address of p.
Rather than a global variable consider using an exported function in the DLL that returns the needed reference/pointer. At the very least name it something more descriptive (unless it was just renamed for the purpose of asking this question).
Is your call to install actually happening in the dll address space (in the debugger, step into the call and check the addresses in the callstack)? Is install defined in a header file or is that extract from a source file? If in a header, it's been inlined into your exe so the dll version of p is never set. This would happen without any linker warning since there are two independent binaries using the same source.
Is MOUSEHOOKSHARED_EXPORT defined in your app? Probably needs to be MOUSEHOOKSHARED_IMPORT for the app (but not the dll).
You're creating a shallow copy of that parameter mParent. At some point, that pointer must be getting set to null (or you're passing it as null), which will result in p also becoming null.

ESP error when sending window messages between threads

I have an Observer class and a Subscriber class.
For testing purposes, the observer creates a thread that generates fake messages and calls CServerCommandObserver::NotifySubscribers(), which looks like this:
void CServerCommandObserver::NotifySubscribers(const Command cmd, void const * const pData)
{
// Executed in worker thread //
for (Subscribers::const_iterator it = m_subscribers.begin(); it != m_subscribers.end(); ++it)
{
const CServerCommandSubscriber * pSubscriber = *it;
const HWND hWnd = pSubscriber->GetWindowHandle();
if (!IsWindow(hWnd)) { ASSERT(FALSE); continue; }
SendMessage(hWnd, WM_SERVERCOMMAND, cmd, reinterpret_cast<LPARAM>(pData));
}
}
The subscriber is a CDialog derived class, that also inherits from CServerCommandSubscriber.
In the derived class, I added a message map entry, that routes server commands to the subscriber class handler.
// Derived dialog class .cpp
ON_REGISTERED_MESSAGE(CServerCommandObserver::WM_SERVERCOMMAND, HandleServerCommand)
// Subscriber base class .cpp
void CServerCommandSubscriber::HandleServerCommand(const WPARAM wParam, const LPARAM lParam)
{
const Command cmd = static_cast<Command>(wParam);
switch (cmd)
{
case something:
OnSomething(SomethingData(lParam)); // Virtual method call
break;
case // ...
};
}
The problem is, that I see strange crashes in the HandleServerCommand() method:
It looks something like this:
Debug Error!
Program: c:\myprogram.exe
Module:
File: i386\chkesp.c
Line: 42
The value of ESP was not properly
saved across a function call. This is
usually the result of calling a
function declared with one calling
convention with a function pointer
declared with a different calling
convention.
I checked the function pointer that AfxBeginThread() wants to have:
typedef UINT (AFX_CDECL *AFX_THREADPROC)(LPVOID); // AFXWIN.H
static UINT AFX_CDECL MessageGeneratorThread(LPVOID pParam); // My thread function
To me, this looks compatible, isn't it?
I don't know, what else I have to look for. Any ideas?
I made another strange observation, that might be related:
In the NotifySubscribersmethod, I call IsWindow() to check if the window to which the handle points, exists. Apparently it does. But calling CWnd::FromHandlePermanent() returns a NULL pointer.
From afxmsg_.h:
// for Registered Windows messages
#define ON_REGISTERED_MESSAGE(nMessageVariable, memberFxn) \
{ 0xC000, 0, 0, 0, (UINT_PTR)(UINT*)(&nMessageVariable), \
/*implied 'AfxSig_lwl'*/ \
(AFX_PMSG)(AFX_PMSGW) \
(static_cast< LRESULT (AFX_MSG_CALL CWnd::*)(WPARAM, LPARAM) > \
(memberFxn)) },
So the signature is LRESULT ClassName::FunctionName(WPARAM, LPARAM), while yours is void ClassName::FunctionName(const WPARAM, const LPARAM). This should not compile, at least under VS2008 it doesn't.
What is your HandleServerCommand declaration in the CServerCommandSubscriber class (in the header file)?
To me, this looks compatible, isn't
it?
Syntactically it looks that way.
I don't know, what else I have to look
for. Any ideas?
Yes: I've had the same problem when compiling a plugin library with debug settings and used in a Release-compiled application.
Basically, the problem looks like a stack corruption.
Since you're running NotifySubscribers in a separate thread, consider using PostMessage (or PostThreadMessage) instead of SendMessage.
This may not be the actual cause of the crash, but the change should be made anyway (as you're switching threading contexts by using SendMessage with no guarding of the data whatsoever.
I eventually decided to do it without window messages and am now posting my workaround here. Maybe it will help someone else.
Instead of letting the observer post window messages to its subscribers, I let the observer put data into synchronized subscriber buffers. The dialog class subscriber uses a timer to periodically check its buffers and call the apropriate handlers if those aren't empty.
There are some disadvantages:
It's more coding effort because for each data type, a buffer member needs to be added to the subscriber.
It's also more space consuming, as the data exists for each subscriber and not just once during the SendMessage() call.
One also has to do the synchronization manually instead of relying on the observer thread being suspended while the messages are handled.
A - IMO - huge advantage is that it has better type-safety. One doesn't have to cast some lParam values into pointers depending on wParam's value. Because of this, I think this workaround is very acceptable if not even superior to my original approach.