C++ uninitialized local variable

You are making the mistake that many make when it comes to functions that require pointer arguments.

When a function requires a pointer as an argument, it doesn’t mean you blindly declare a pointer and pass it to the function. What the function is asking for is an address-of an existing, valid, entity.

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

The DWORD‘s above are valid, and all that is done is pass the address of these variables to the function.

The other mistake that is related to this (not a bug, as it will give the desired results, but still a “mistake”) is to declare a pointer, have it point to somewhere valid, and then pass it to the function. In other words:

PDWORD major, minor, build;
major = new DWORD;
minor = new DWORD;
build = new DWORD;
GetOSVersion(major, minor, build);
delete major;
delete minor;
delete build;

or

PDWORD pmajor, pminor, pbuild;
DWORD major, minor, build;
pmajor = &major;
pminor = &pminor;
pbuild = &build;
GetOSVersion(pmajor, pminor, pbuild);

I have seen code written in this manner. This indicates that the programmer does not have a clear understanding of what it means when a function requires a pointer as an argument. The programmer erroneously believes that a pointer must be declared, have it point somewhere valid, and then pass this pointer.

Yes, you get the results without crashing, but it is a waste of time to call the allocator (new / delete), or if not calling the allocator, create unnecessary pointer variables which unnecessarily obfuscates the code.

So the easiest way is the first example above. Just declare non-pointer types, and just pass the address.

Leave a Comment