I have a quick question regarding updating an array in C. I'm including the code I have written, along with the debug/print statement output.
//struct
typedef struct Server {
char* name;
pid_t pid;
} Server;
//global vars
int num_servers; //the number of servers (num_servers-1 is index in array)
Server* servers; //the array of servers
int size; //size of the array
//instantiation inside main method
num_servers = 0;
servers = NULL; //null instantiation allows us to use realloc all time
size = 0;
//inside main function and a while loop
//check if we need to resize the array
if(num_servers >= size){
resizeArray(true);
}
//create struct
Server s = createServer(args[3], id);
//add to array
insertServer(s);
printf("Main: last server has name: %s\n", servers[num_servers-1].name); //debug
++num_servers;
/*
* creates/returns a server with the specified characteristics
* name - the name of server]
* id - the id of the server
*/
Server createServer(char* name, pid_t id){
Server s;
s.name = malloc(strlen(name) * sizeof(char));
strcpy(s.name, name);
s.pid = id;
printf("Created server with name: %s\n", s.name); //debug
return s;
}
/*
* appends server to end of array
* serv - the server struct to insert
*/
int insertServer(Server serv){
printf("Inserting server with name: %s\n", serv.name); //debug
//allocate memory
servers[num_servers-1].name = malloc(strlen(serv.name) * sizeof(char));
//actually copy
strcpy(servers[num_servers-1].name, serv.name);
servers[num_servers-1].pid = serv.pid;
printf("The last server in array now has id of: %s\n", servers[num_servers-1].name);
return 0;
}
When I run the while loop for the first time and insert a server, the program runs correctly (all the print statements output the name of the server). However, as soon as the while loop runs again, I get a seg fault. Using GDB I found that while the memory for the array appears to be allocated, the actual structs (and their information) do not appear in the array. Any idea as to why the information is present in the heap during the while loop, yet dissapears when it runs again? Thank you.