I have the following code:
void SendRequest(HINTERNET connection, LPCWSTR method, LPCWSTR referer,LPCWSTR path,WINHTTP_STATUS_CALLBACK whCallback){
HINTERNET request;
request=WinHttpOpenRequest( connection, 0,path,0,referer,WINHTTP_DEFAULT_ACCEPT_TYPES,0);
WinHttpSetStatusCallback(request, (WINHTTP_STATUS_CALLBACK)whCallback,WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS,0);
REQUEST_CONTEXT cpContext;
WinHttpSendRequest(request,WINHTTP_NO_ADDITIONAL_HEADERS,0,NULL,NULL,NULL,(DWORD_PTR)&cpContext);
};
WinHttpSendRequest does not block, so once it is executed, the function ends. However, WinHttpSendRequest callback to another function with the cpContext as a parameter. So my question is, doe cpContext gets destroyed after the function ends? Does this result in a a memory leak since there is no way to access cpContext outside the function? How can I do this in best C++ practice?
cpContextis destroyed at the end of the function. This results in undefined behavior becausecpContextmay be destroyed before the callback is invoked. If you dereference the pointer to it from within the callback, this is undefined behavior. One way to solve this would be to avoid using a locally-scoped variable:Don’t forget to
deleteit within the callback function.The leak would be the
HINTERNEThandle, unless you are closing it in your callback. This handle needs to be closed withWinHttpCloseHandle, but you cannot close it while the asynchronous request is active.