简体   繁体   中英

windows C++ opening printer with documentproperties get C6836 “Write Overrun” Code analysis warning

In the following code:

// If GetPrinter didn't fill in the DEVMODE, try to get it by calling
// DocumentProperties...
if (pi2->pDevMode == NULL)
{
    dwNeeded = DocumentProperties(NULL, hPrinter,
        printerName,
        NULL, NULL, 0);

    if (dwNeeded <= 0)
    {
        GlobalFree(pi2);
        ClosePrinter(hPrinter);
        return FALSE;
    }

    pDevMode = (DEVMODE *)GlobalAlloc(GPTR, dwNeeded);
    if (pDevMode == NULL)
    {
        GlobalFree(pi2);
        ClosePrinter(hPrinter);
        return FALSE;
    }

    lFlag = DocumentProperties(NULL, hPrinter,
        printerName,
        pDevMode, NULL,
        DM_OUT_BUFFER);

    if (lFlag != IDOK || pDevMode == NULL)
    {
        GlobalFree(pDevMode);
        GlobalFree(pi2);
        ClosePrinter(hPrinter);
        return FALSE;
    }

    pi2->pDevMode = pDevMode;
}

On the line

lFlag = DocumentProperties(NULL, hPrinter,
printerName,
pDevMode, NULL,
DM_OUT_BUFFER);

When I run Visual Studio 2012 "Code analysis" feature it throws warning:

C6386 Write overrun Buffer overrun while writing to 'pDevMode': the writable size is 'dwNeeded' bytes, but '220' bytes might be written. Invalid write to 'pDevMode', (outside its writable range)

The code functions fine, but wondering how to fix this warning from occurring (preferably without disabling warning)

The help page for this error does not seem to apply (or I can't figure how it does) http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&l=EN-US&k=k(C6386)&rd=true

The SAL annotation for DocumentProperties cannot express that DEVMODE is a structure than might be larger than its declared size. The function doesn't also take an argument that states the passed size of the DEVMODE. Nor does the structure have a single field that states the size. So an annotation like __out_bcount_opt or __out_bcount_part could not be used.

It is an issue with all winapi functions that take a DEVMODE. It is a structure that dates from the stone age, long before SAL was ever on the horizon. If Microsoft could do it all over again then they would do this differently. Too late now.

Nothing you can do about it beyond knowing that you got it right and the tool got it wrong. It is just a warning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM