我有一个关于在C中更新数组的快速问题。我包括我编写的代码,以及调试/打印语句输出。
//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循环并插入服务器时,程序正确运行(所有print语句都输出服务器的名称)。但是,只要while循环再次运行,我就会遇到一个seg错误。使用GDB我发现虽然数组的内存似乎已分配,但实际的结构(及其信息)不会出现在数组中。知道为什么信息在while循环期间存在于堆中,但是当它再次运行时消失了吗?谢谢。
答案 0 :(得分:0)
在这段代码中你没有为c-string分配足够的内存('\ 0'-char 又名终止 e的字符的遗忘字节):
s.name = malloc(strlen(name) * sizeof(char));
strcpy(s.name, name);
尝试使用 strdup :
s.name = strdup(name);