Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct usage of GetComputerName - Do I need to reserve extra space for null character

Tags:

c++

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);
like image 629
Cheok Yan Cheng Avatar asked Dec 06 '22 23:12

Cheok Yan Cheng


1 Answers

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);
like image 193
Greg Hewgill Avatar answered Dec 22 '22 01:12

Greg Hewgill