If the documentation says you must call a function, then you must. Perhaps the function does nothing, but that does not mean that it will not do anything in the future.
Today's example is the GetEnvironmentStrings function, which returns all the environment variables of the current process in one block for study at leisure. When you are done with this, it is assumed that you are using FreeEnvironmentStrings. That is what the documentation says, and if you do this,
you're in good shape .
However, some have noticed that in Windows NT4, the version of FreeEnvironmentStrings for Unicode does nothing. In other words, the UniCode environment variable block does not need to be deleted. When you call GetEnvironmentStrings, the kernel simply returns a direct pointer to the actual environment variables (which, since this is Windows NT, is stored in Unicode). Since nothing stands out, nothing needs to be deleted.
The problem with this is that if someone calls SetEnvironmentVariable at this time, the block of environment variables will change right in the hands of the one who called GetEnvironmentStrings.
')
Oops.
To fix this (
in comments Raymond Chen writes that it was done in Windows Vista — L. C. ), the GetEnvironmentStrings function was changed, and returns a copy of the block of environment variables, even if you call the Unicode version. The corresponding FreeEnvironmentStrings function removes this copy.
Programs that follow the specifications and call FreeEnvironmentStrings (although the function hasn’t done anything before) are fine. The call to FreeEnvironmentStrings now frees the memory, and all is well.
Programs made according to implementation, not specification, are now in a world of pain. If they just missed the "useless" call to FreeEnvironmentStrings, they will have a memory leak. On the other hand, if they called FreeEnvironmentStrings, but they still used the environment block, they would have to refer to the wrong place in the heap and all the chaos that might follow from this.
There is always some reason for the rules, which at first glance look stupid. ("Call this function that does nothing"). Changes in implementation may make them not so stupid in the future.
(Thanks to my colleague Neill Clift for the information that led to today's article)
Raymond Chen is a well-known developer of the Windows Shell team. In Microsoft since 1992, he worked on OS / 2, Windows 95, DirectX and the latest versions of Windows.
Known for his blog The Old New Thing, which tells about the history of Windows programming with a focus on backward compatibility.
UPD: Transferred to a new team blog. Thanks for the karma!