Correct usage of GetComputerName - Do I need to reserve extra space for null character
I was wondering, what is the correct usage of GetComputerName. Should it be
TCHAR computerName[1024 + 1];
DWORD size = 1024;
GetComputerName(computerName, &size);
开发者_开发问答
or
TCHAR computerName[1024];
DWORD size = 1024;
GetComputerName(computerName, &size);
The size passed in the lpnSize
parameter reflects the amount of space available in the buffer, including space for the null terminator. Either of your statements will work, because in the first one you're just allocating one more byte than what you're saying is available.
You may want to use MAX_COMPUTERNAME_LENGTH
instead, which is much less than 1024.
TCHAR computerName[MAX_COMPUTERNAME_LENGTH + 1];
DWORD size = sizeof(computerName) / sizeof(computerName[0]);
GetComputerName(computerName, &size);
The documentation says explicitly:
The buffer size should be large enough to contain MAX_COMPUTERNAME_LENGTH + 1
And then:
If the buffer is too small, the function fails and GetLastError returns ERROR_BUFFER_OVERFLOW. The lpnSize parameter specifies the size of the buffer required, including the terminating null character.
Which means that you either:
- Create a buffer with length
MAX_COMPUTERNAME_LENGTH + 1
- Create a smaller buffer, but then be sure to catch the error value in case it's too small. In this case note that On input, [lpnSize] specifies the size of the buffer, in TCHARs. so the second version is correct
IMHO, you may try:
CString value;
DWORD size = 1024;
if(!GetComputerName(value.GetBufferSetLength(size), &size)){
value = _T("");
}
return value;
size
is the size of the buffer (on input), not the length of the string. On output it is the length of the string. Your second version is correct. The first one does not hurt, though. But please do consider using MAX_COMPUTERNAME_LENGTH instead of some hard-coded value.
精彩评论