Home > OS >  WinInet Access Violation in HttpOpenRequest()
WinInet Access Violation in HttpOpenRequest()

Time:11-15

I am trying to upload a file to a PHP page using WinInet. I'm getting an Access Violation on one of the functions, but can't see why. I've built the code from an example page.

Here is the code:

HINTERNET aInternet=InternetOpen("My-Custom-Agent/1.0",INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
HINTERNET aConnect=InternetConnect(aInternet,"www.myserver.com",INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
if (aConnect)
{
    HINTERNET aRequest=HttpOpenRequest(aConnect, (const char*)"POST","myphppage.php", NULL, NULL, (const char**)"*/*\0",0,1);
    // ^^
    // Exception happens on this line
    // Exception thrown at 0x70C85B7C (ininet.dll) in TestApp.exe:
    // 0xC00000005: Access violation reading location 0x002A2F2A
    //
}

When I download from the server with InternetOpenURL(), everything seems fine. It just doesn't like what I'm doing somewhere here. Any clue what I'm doing wrong?

CodePudding user response:

Per the HttpOpenRequest() documentation:

[in] lplpszAcceptTypes

A pointer to a null-terminated array of strings that indicates media types accepted by the client. Here is an example.

PCTSTR rgpszAcceptTypes[] = {_T("text/*"), NULL};

Failing to properly terminate the array with a NULL pointer will cause a crash.

You are passing in a pointer to a single null-terminated string, incorrectly type-casted to const char**:

lplpszAcceptTypes -> "*/*"

But the function requires a pointer to an array of pointers to null-terminated strings:

                     -----
lplpszAcceptTypes -> | 0 | -> "*/*"
                     |---|
                     | 1 | -> NULL
                     -----

See the difference? So, the function misinterprets the contents of your string literal as an array of pointers, which it is not, hence the AV crash.

Use this instead:

LPCSTR rgpszAcceptTypes[] = {"*/*", NULL};
HINTERNET aRequest = HttpOpenRequest(aConnect, "POST", "myphppage.php", NULL, NULL, rgpszAcceptTypes, 0, 1);
  • Related