Is there a way to have buffer functions not waste so much memory?
buffer functions like GetWindowText(), GetModuleFileName(), SHGetFolderPath() make me angry because you almost always waste so much memory in the buffer. Is开发者_StackOverflow中文版 there a way to have them not waste so much memory?
"make me angry"? Are you a six-year-old? :-)
I'm not entirely certain what your complaint is here. You can restrict how much is returned from GetWindowText
and GetModuleFileName
quite easily (at the cost of losing information) by specifying your own maximum length.
But, if you want to be able to get the whole thing, you need space for it. There's no way around that. SHGetFolderPath
is not so accomodating but it's only MAXPATH
characters after all.
I find it hard to believe that someone under Windows is concerned about the very small allocation needed for storing these data items. You do know that you have absolute bucketloads of address space, yes? And you can share the memory, reusing it for more than one thing (though not concurrently of course) if you're really worried.
Typically you'll call those functions with a buffer that has been allocated on the stack. There's virtually no cost to allocating enough space on the stack, because it becomes unused the moment you return from your function.
If you try to do something that allocates only as much memory as is required (such as calling GetWindowText()
repeatedly with an increasing buffer size), you'll waste time instead of memory. Time (and therefore energy) is much more costly.
There are different solutions for different functions. For example, a call to GetWindowText() can be preceded by a call to GetWindowTextLength(). With GetModuleFileName(), you can pass a small buffer, and see if the filename fits. There are other functions where if you pass a null for your buffer, they will return the exact size you need to allocate for your buffer the next time you cal the function.
In general, though, you're making a big deal out of a small problem. Memory is very cheap these days, and I'd be very surprised if a file name, for example, is causing you to exhaust memory. Just allocate a 32k buffer (maximum NTFS path length) and be done with it.
精彩评论