3 ms·
Yes as a simple example of a wrapper: std::string nicerGetComputerName() { char buf[1024]; DWORD len = sizeof(buf); memset(buf, 0,
by ape4 6y ago
Yes as a simple example of a wrapper:
std::string nicerGetComputerName() {
char buf[1024];
DWORD len = sizeof(buf);
memset(buf, 0, sizeof(buf));
GetComputerNameA(buf, &len);
return buf;
}
- criddell 6y agoWhat encoding will the string returned from GetComputerNameA be in? Is it the code page for the current regional setting? Wouldn't it be safer to use GetComputerNameW to get a UTF-16 string?
- jiggawatts 6y ago#1) GetComputerNameA can fail. You didn't check the error message or convert it into a C++ exception. #2) You probably want GetComputerNameW. GetComputerNameA uses an unspecified encoding that you'd have to handle. #3) A 1KB buffer is excessive! Over-sized buffers can blow through the L1 cache all too easily, slowing down applications. It's also stack allocated, and this can be a problem in some scenarios. #4) You're forcing the computer name to be heap allocated. This can also be problematic in some scenarios, and is slower. GetComputerName might be used in logging scenarios that are already trying to handle cases such as "out of memory"! Allocating more memory may be unacceptable. You get the idea.
- saagarjha 6y agoFYI: char buf[1024] = {0};