Hi all.
I'm trying to write a C function that returns a dynamic list of servers. My pointer memory is a bit rusty so I just wanted to check if the code below is correct. Although the output is as expected, i.e. 3 servers with IP & name, and there appears to be no memory leaks (used Visual Leak Detector) I just want to triple check. Note, I'm just interested in knowing if the pointer usage is correct rather than actual logic or error checking. I'm using VS 2013 express. Thanks in advance.
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct serverInfo
{
char serverName[50];
char serverIP[20];
};
int getServerListTest(serverInfo** pServers);
int _tmain(int argc, _TCHAR* argv[])
{
serverInfo *serverList = (serverInfo*)calloc(1, sizeof(serverInfo));
serverInfo **serverListPtr = &serverList;
int serverCount = getServerListTest(serverListPtr);
for (int i = 0; i < serverCount; i++)
{
printf("ip:%s name:%s\n", (*serverListPtr+i)->serverIP, (*serverListPtr+i)->serverName);
}
free(serverList);
serverListPtr = NULL;
getchar();
return 0;
}
int getServerListTest(serverInfo** pServers)
{
serverInfo* current = NULL;
int serverCount= 0;
char serverNo[5];
for (int i = 0; i < 3; i++)
{
if (serverCount > 0)
{
current = (serverInfo*)realloc((*pServers), sizeof(serverInfo) * (serverCount+1));
if (current)
{
pServers = ¤t;
}
else
{
return -1;
}
}
_itoa(serverCount+1, serverNo, 10);
strcpy((*pServers + serverCount)->serverIP, "10.10.100.10");
strcat((*pServers + serverCount)->serverIP, serverNo);
strcpy((*pServers + serverCount)->serverName, "Server");
strcat((*pServers + serverCount)->serverName, serverNo);
serverCount++;
}
return serverCount;
}