【问题标题】:Updating dynamic array in c在c中更新动态数组
【发布时间】:2023-03-28 18:39:01
【问题描述】:

我有一个关于在 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循环并插入服务器时,程序运行正常(所有打印语句都输出服务器的名称)。但是,一旦 while 循环再次运行,我就会遇到段错误。使用 GDB,我发现虽然数组的内存似乎已分配,但实际的结构(及其信息)并未出现在数组中。关于为什么在while循环期间信息存在于堆中,但当它再次运行时消失的任何想法?谢谢。

【问题讨论】:

  • 发布的代码没有while 循环。它甚至不是可编译的代码。请发布显示问题的Minimal, Complete, and Verifiable example
  • 请在此处阅读如何提问并提供一个最小示例:stackoverflow.com/help/mcve
  • 你有一个非一的错误,并且将写入超出分配内存的范围(不要忘记C中的char字符串实际上称为null终止 字符串)。
  • 哦,你真的有两个个错误。对于第一个“服务器”,当num_servers 为零时,那么num_servers - 1 是什么?而且你有内存泄漏。
  • 最后,我推荐你阅读this old question关于复制结构的内容。它比你想象的要简单得多。

标签: c arrays pointers dynamic


【解决方案1】:

在此代码部分中,您为 c 字符串分配的内存不足('\0'-char aka char of terminate 的忘记字节):

s.name = malloc(strlen(name) * sizeof(char));
strcpy(s.name, name);

尝试使用strdup

s.name = strdup(name);

【讨论】:

    猜你喜欢
    • 2021-06-12
    • 2015-01-11
    • 2019-05-10
    • 2020-04-25
    • 2014-12-04
    • 2011-01-28
    • 1970-01-01
    • 2018-05-26
    • 2015-02-01
    相关资源
    最近更新 更多