在C语言中动态分配字符串数组的内存

3
我正在尝试使用C语言将Linux系统上的所有挂载点列表存储到一个字符串数组中。我关注于这段代码。
int i = 0;
char **mountslist = malloc(1024 * sizeof(char *));

/*
 * Make sure that the number entries in the array are less than the allocated
 * 1024 in the absurd case that the system has that many mount points.
 */
while (i < 1024 && (ent = getmntent(mounts))) {
    /*
     * The output of getmntent(mounts) goes down to
     * the next mount point every time it is called.
     */
    mountslist[i] = strdup(ent->mnt_dir);
    i++;
}

我想知道如何动态分配mountslist数组的条目数(当前静态设置为1024),以避免限制和浪费内存。如果在声明mountslist时有最终值i,则可以使用char *mountslist[i];char **mountslist = malloc(i * sizeof(char *));


3
请查阅realloc函数。 - user253751
4k(或64位系统上的8k)不会让你破产。我认为你已经在这里浪费了足够的时间。但如果你要编写C代码,你应该学习关于“realloc”的知识。 - rici
@rici 我同意我这里的内容可能是无意义的,而且我现在的代码已经很好了。我只是发布了它,因为我找不到答案,所以现在其他处于类似情况的人就有了一个答案。 - Billy
1
它只有char *大小的1024倍。之后你可以简单地realloc(向下)即可。 - jarmod
根据您的进一步使用情况,使用链表而不是数组可能更好。这样,您可以分配实际需要的条目数量。 - Serge
显示剩余2条评论
1个回答

2

您可以使用realloc函数来改变已分配内存块的大小:

int i = 0;
int len = 10;
char **mountslist = malloc(len * sizeof(char *));

while ((ent = getmntent(mounts)) != NULL) {
    if (i >= len) {
        len *= 2;
        char **tmp = realloc(mountslist, len * sizeof(char *));
        if (tmp) {
            mountslist = tmp;
        }
    }
    mountslist[i] = strdup(ent->mnt_dir);
    i++;
}

如上所示,一个好的规则是在空间不足时将分配的空间加倍。这可以防止过多调用 realloc,每次调用可能会移动已分配的内存。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接