Proper use of GetComputerName - Do I need to reserve extra space for the null character

I was wondering what the proper use of GetComputerName is . If it will be

TCHAR computerName[1024 + 1]; DWORD size = 1024; GetComputerName(computerName, &size); 

or

 TCHAR computerName[1024]; DWORD size = 1024; GetComputerName(computerName, &size); 
+4
source share
4 answers

The size passed in the lpnSize parameter reflects the amount of free space in the buffer, including space for the null terminator. Any of your statements will work, because in the first you just allocate one more byte than what you say is available.

Instead, you can use MAX_COMPUTERNAME_LENGTH , which is much less than 1024.

 TCHAR computerName[MAX_COMPUTERNAME_LENGTH + 1]; DWORD size = sizeof(computerName) / sizeof(computerName[0]); GetComputerName(computerName, &size); 
+9
source

The documentation states explicitly:

The buffer size must be large enough to add MAX_COMPUTERNAME_LENGTH + 1

And then:

If the buffer is too small, the function does not work and GetLastError returns ERROR_BUFFER_OVERFLOW. The lpnSize parameter specifies the size of the required buffer, including the terminating null character.

This means that you either:

  • Create a buffer of length MAX_COMPUTERNAME_LENGTH + 1
  • Create a smaller buffer, but then be sure to catch the error value if it is too small. In this case, note that at the input [lpnSize] sets the size of the buffer in TCHAR. therefore the second version is correct.
+2
source

IMHO, you can try:

 CString value; DWORD size = 1024; if(!GetComputerName(value.GetBufferSetLength(size), &size)){ value = _T(""); } return value; 
+1
source

size - the size of the buffer (at the input), not the length of the string. The output is the length of the string. Your second version is correct. However, the first does not hurt. But please consider using MAX_COMPUTERNAME_LENGTH instead of some encoded value.

0
source

Source: https://habr.com/ru/post/1335945/


All Articles