February 18th, 2010

Don't forget to double-null-terminate those strings you pass to SHFileOperation

About once every two months for the past six months (I stopped checking further back), somebody reports a problem with the SHFileOperation function. Often, they don’t include very much information at all. They just say, “I call the function and it doesn’t work.” Here’s an example:

I’m hitting a problem with SHFileOperation when using it to frob files in the gonzo directory when the user’s SID ends in an odd number.

    //
    // Delete the file.
    // szDeletePath contains the full path to the file.
    //
    shFileOp.hwnd = NULL;
    shFileOp.wFunc = FO_DELETE;
    shFileOp.pFrom = szDeletePath;
    shFileOp.pTo = NULL;
    shFileOp.fFlags = FOF_NO_UI;
    iRet = SHFileOperation( &shFileOp );

The function returns file not found, but the file is definitely there.

If you read the variable names carefully, you can see the problem.

The pFrom and pTo members of the SHFILEOPSTRUCT structure are double-null-terminated strings. (There’s even a callout box for this in the MSDN documentation.) But a variable named szDeletePath is probably a single-null-terminated string. (The name for a double-null-terminated string would be szzDeletePath.)

My psychic powers tell me that szDeletePath is not double-null-terminated.

So far, my psychic powers haven’t failed.

Now, you might say that the fact that people make this mistake so often is a sign that the function is flawed. And if the function were designed today, I would agree with you. But this function in its public form is over fifteen years old (and in its private form, is around 20 years old), and back in those days, programmers were assumed to have the time to understand the subtleties of what they were doing.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.