我有一个关于在C中更新数组的快速问题。我要包括我编写的代码以及debug / print语句输出。
//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;
}
当我第一次运行while循环并插入服务器时,程序将正确运行(所有打印语句均输出服务器的名称)。但是,一旦while循环再次运行,我就会遇到段错误。使用GDB,我发现虽然阵列的内存似乎已分配,但实际的结构(及其信息)并未出现在阵列中。关于为什么信息在while循环期间存在于堆中,而在再次运行时却消失的任何想法?谢谢。
最佳答案
在这段代码中,您没有为c字符串分配足够的内存(“ \ 0” -char或终止字符char)的忘记字节:
s.name = malloc(strlen(name) * sizeof(char));
strcpy(s.name, name);
尝试使用strdup:
s.name = strdup(name);