I am trying to write a sample program which can parse a string and store its host name and port number separately.
After I identify number of characters to write for the server name(abcdef), removing http prefix, I allocate that much and try to write 6+1 wide chars from source string server.
But I end up writing 9 wide chars( swprintf returns len=9), i.e. serverName becomes = abcdef:80 not abcdef.
msdn document for swprintf states that the second parameter count is max. no. of wide chars to be written. so why does it write till the end of source string?
Am I missing anything? Let me know. Thanks
void main()
{
UINT8 server [] = "http://abcdef:80";
CHAR* port = NULL;
SHORT portnum = 0;
WCHAR* serverName = NULL;
SIZE_T inBufLen = 0;
SIZE_T outBufBytes = 0;
port = strrchr(server, ':');
if (port != NULL)
{
portnum = atoi(port+1);
printf(": at %d ", (int)(port-server));
SIZE_T serverLen = port - server;
if (strstr(server, "http") != NULL)
{
serverLen -= 7; //for eliminating characters from "http://"
inBufLen = serverLen + sizeof(CHAR);
outBufBytes = inBufLen * sizeof(WCHAR);
serverName = (WCHAR*)malloc(outBufBytes);
ZeroMemory(serverName, outBufBytes);
int len = swprintf_s(serverName, outBufBytes, L"%S", server+7);
printf("%d", len);
}
else
{
serverName = (WCHAR*)malloc((serverLen + sizeof(CHAR)) * sizeof(WCHAR));
ZeroMemory(serverName, (serverLen + sizeof(CHAR)) * sizeof(WCHAR));
swprintf_s(serverName, (serverLen + sizeof(CHAR)) * sizeof(WCHAR), L"%S", (CHAR*)server + 7);
}
}
}