Search code examples
c++windowsmsdncreatefile

CreateFile() return an invalid pointer with the address FFFFFF


I just want to read a file using the function CreateFile such as following :

#include <iostream>
#include <windows.h>
#include <stdio.h>
int main(int argc, char **argv)
{
    PIMAGE_DOS_HEADER pImageDosHeader;
    HANDLE hFile = NULL;
    HANDLE hMapObject;
    PUCHAR uFileMap;
    if (argc < 2)
        return (-1);
    std::cout << "hFile=" << hFile << std::endl;
    if (!(hFile = CreateFile((LPCWSTR)argv[1], GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ,
        NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)))
    {
        return (-1);
    } else {
        std::cout << argv[1] << std::endl;
        std::cout << "hFile=" << hFile << std::endl;
        getchar();
    }
    return (0);
}

The problem is that the output is like below :

hFile=000000 (the pointer is initialized to NULL -> OK)

hFile=FFFFFF (invalid pointer)

Does anyone can help me, please ? Thanks in advance for your help.


Solution

  • The following:

    if (!(hFile = CreateFile(...)))
    

    is not how you check for errors.

    From the documentation:

    If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.

    INVALID_HANDLE_VALUE is -1, or 0xFFFFFFFFF in hex. You need to call GetLastError() to find out what happened.