Even if the function does nothing, call it when the documentation requires it, because tomorrow it can do something

Original author: Raymond Chen
  • Transfer
If the documentation says that you should call a function, then you should. 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 your leisure. When you are done with this, it is assumed that you are using FreeEnvironmentStrings. This is what the documentation says, and if you do, you're in ( you're in good shape ).

However, some have noticed that on Windows NT4, the Unicode version of FreeEnvironmentStrings does nothing. In other words, the Unicode block of environment variables does not need to be deleted. When you call GetEnvironmentStrings, the kernel simply returns a direct pointer to the real environment variables (which, since it is Windows NT, are 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.


To fix this ( in the comments, Raymond Chen writes that this was done in Windows Vista - L. Ts.), the GetEnvironmentStrings function has been changed, and returns a copy of the block of environment variables, even if you call the Unicode version. The corresponding FreeEnvironmentStrings function deletes this copy.

Programs that follow the specifications and call FreeEnvironmentStrings (even though the function hasn't done anything before) are fine. Calling FreeEnvironmentStrings now frees memory, and all is well.

Programs made according to implementation, not specification, are now in the world of pain. If they just missed the “useless” call to FreeEnvironmentStrings, they would have a memory leak. On the other hand, if they called FreeEnvironmentStrings, but still used the environment block, they would have access to the wrong place in the heap and all the chaos that could result from this.

There is always some reason for rules that at first glance look silly. (“Call this function that does nothing”). Changes in implementation may make them not so dumb 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 talks about the history of Windows programming with a focus on backward compatibility.

UPD: Moved to a new collective blog. Thanks for the karma!

Also popular now: