Just to see what happens, a customer called SetÂClipboardData( and passed a memory block that was intentionally not null-terminated. They found that when they subsequently pasted the string (say, into Notepad), the last character didn’t get pasted.
As a second experiment, they over-allocated the buffer by one byte, still refused to null-terminate the string, and they found that all of the characters made it.
There’s nothing in the documentation for SetÂClipboardÂData that contains any warning about trying to put non-null-terminated strings on the clipboard. What’s going on?
While it’s true that there nothing in the SetÂClipboardÂData documentation, there is text in the Standard Clipboard Formats documentation.
| CF_TEXT 1 |
Text format. Each line ends with a carriage return/linefeed (CR-LF) combination. A null character signals the end of the data. Use this format for ANSI text. |
The documentation says that you need to pasa a null-terminated string. If you don’t, then you have violated a requirement, and the behavior is undefined. And one legal manifestation of undefined behavior is “Secretly removes the last character of the string.”
What’s happening is that the clipboard manager says, “Okay, I know that CF_TEXT requires a null-terminated string, I’m going to set the last byte of the buffer to null just to make sure that it really is null-terminated.”
How does the clipboard manager know where the last byte of the buffer is, if it isn’t null-terminated?
It uses the GlobalÂSize function to learn the size of the buffer. That’s why over-allocating the buffer by one byte fixes the problem. The GlobalÂSize function returns the buffer size, which includes the extra garbage byte, and then the clipboard manager says, “You numbskull, you forgot to null-terminate the string. I will change the last byte of the buffer to a null so that it’s properly null-terminated, like you should have done in the first place.”
The clipboard manager already has to use the GlobalÂSize function to figure out the size of the buffer you passed to SetÂClipboardÂData: In general, there is no requirement that that clipboard data be null-terminated, and in particular, the clipboard manager doesn’t know anything about the internal format of custom clipboard formats, so it just has to trust that the buffer is properly formatted. (And consumers should validate that the data is indeed properly formatted.)
Now, you shouldn’t be counting on the clipboard manager doing this sort of autocorrection for you. Just null-terminate the data properly. Everybody will be happier.
0 comments
Be the first to start the discussion.