Trying to add another element to a struct array in C (Windows specific, using VS2019 Community). Works fine, until I try to assign the return value of realloc to the original array. The code in main (declarations and initialization, as well as calling code) is as follows:
// server.h
struct server {
wchar_t* name;
wchar_t ip_address[16];
int port;
};
// main.c
static int nb_servers = 0;
static struct server* servers = NULL;
void add_server(wchar_t* name, wchar_t ip_address[16], wchar_t* port)
{
struct server newserver;
newserver.name = name;
wcsncpy(newserver.ip_address, ip_address, 16);
char* port_char = malloc(6);
if (port_char == NULL) {
exit(EXIT_FAILURE);
}
size_t i;
wcstombs_s(&i, port_char, 6, port, _TRUNCATE);
int port_int = 0;
str2int(&port_int, port_char, 10);
newserver.port = port_int;
// add to servers
nb_servers = server_add(&servers, &newserver, nb_servers);
}
Then in another file, this is where I try to add the new server to the list:
// server.c
int server_add(struct server** servers, struct server* myserver, int nb_servers)
{
struct server* tmp = (struct server*) realloc(*servers, (nb_servers + 1) * sizeof(struct server));
if (tmp == NULL) {
exit(EXIT_FAILURE);
}
tmp[nb_servers].name = (wchar_t*) calloc(strlen(myserver->name), sizeof(wchar_t));
if (tmp[nb_servers].name == NULL) {
exit(EXIT_FAILURE);
}
wcsncpy(tmp[nb_servers].name, myserver->name, strlen(myserver->name));
wcsncpy(tmp[nb_servers].ip_address, myserver->ip_address, 16);
tmp[nb_servers].port = myserver->port;
*servers = tmp; // this only copies the first value [0]
// also tried **servers = *tmp and other combinations, nothing seems to work.
return ++nb_servers;
}
But only the first value is 'copied', or rather only servers[0] point to a valid object. However, tmp[0] to tmp[nb_servers - 1] are valid and contain the correct data. I'm using a similar reallocation mechanism to shrink the array in a remove_server method and that same reassignment works in that case.
Question: How to correctly add a struct item to an array of structs by dynamically reallocating memory?