C++ uninitialized local variable

前端 未结 5 675
夕颜
夕颜 2020-11-27 23:41

I have a function:

VOID GetOSVersion(PDWORD major, PDWORD minor, PDWORD build)
{
    OSVERSIONINFO osver;
    ZeroMemory(&osver, sizeof(OSVERSIONINFO));
         


        
5条回答
  •  粉色の甜心
    2020-11-28 00:32

    You probably meant to have your variable declarations and to call your function like this

    DWORD major;
    DWORD minor;
    DWORD build;
    GetOSVersion(&major, &minor, &build);
    

    You use pointers to reference the output parameters, thus these need to point them to valid memory addresses. You can refer to those variables to get a valid pointer using the 'address-of' (&) operator as shown above.


    With c++ you can use by reference parameters, which will make things a bit clearer

    VOID GetOSVersion(DWORD& major, DWORD& minor, DWORD& build) {
        OSVERSIONINFO osver;
        ZeroMemory(&osver, sizeof(OSVERSIONINFO));
        osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
        GetVersionEx(&osver);
        // Note there's no check needed if the pointers are valid!
        major = osver.dwMajorVersion;
        minor = osver.dwMinorVersion;
        build = osver.dwBuildNumber;
    }
    
    DWORD major;
    DWORD minor;
    DWORD build;
    GetOSVersion(major, minor, build);
    

    No need to call the new() allocator (and bother with correct dynamic memory allocation management) with any of the above samples in 1st place.

提交回复
热议问题