C++ uninitialized local variable

前端 未结 5 685
夕颜
夕颜 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:25

    You are probably not getting an error but a warning (but you might have configured your complier to treat warnings as errors).

    If executed, your program will segfault because you are writing to the memory pointed to by them but as they are uninitialized they contain invalid/random addresses.

    Possible solution

    PDWORD major = new DWORD;
    PDWORD minor = new DWORD;
    PDWORD build = new DWORD;
    

    assuming PDWORD is defined to be *DWORD.

    Do not forget the deletes!

    edit: Actually its much more sensible to allocate these on the stack – see user2451677’s answer.

提交回复
热议问题