Sunday, 06 November, 2005

Silly API Functions

Sometimes I wonder what a programmer was thinking when he came up with a function.  Today's laugh maker is the Windows API function GetConsoleTitle, used to return the text displayed in the title bar of a console window.  The function prototype is:

DWORD GetConsoleTitle(LPTSTR lpConsoleTitle, DWORD nSize);

You pass it a pointer to a string and a number that says how long the string is.  If the string you pass is long enough, the function will fill your string with the title bar text and return the length of the text.  Simple.  Right?  Don't I wish.

The documentation says, "The total size of the buffer required will be less than 64K."  That's nice to know.  I'd hate to think that somebody would make the window's title bar text longer than 65,000 characters..

The real kicker is the discussion of the return value:

So if the buffer I pass isn't big enough, what do I do?  I guess the only safe way to call this function is to allocate 64K bytes (or is it 64K characters?) for the buffer.  Otherwise I run the risk of the function failing and being forced to allocate 64K anyway.

The GetWindowsDirectory function, by the way, isn't much better.  Its return value is described thusly:

Here I have to check the return value against the length that I passed in order to ensure that the buffer I sent was large enough.

I chose examples from the Windows API, but that's not the only API that has screwy functions like this.  The standard C library is chock full of similar oddities, as are many Linux libraries that I've worked with.

I understand that these particular API functions were written long ago and maybe I can give a little leeway to the programmers who designed them and the managers who allowed them to be published.  What I don't understand, though, is how new APIs with similar warts get approved.  Is it really so bad to have a separate function that will return the required size?