c - 过度使用 realloc

标签 c memory-management realloc

将数据读入字符串时,使用尽可能多的 realloc 是否更好?是获得正确内存量所必需的,还是使用更少的内存更好 realloc的但最终可能会出现未使用的内存?

例如,这样更好吗:

char c;
int count = 1;
char* s = malloc(sizeof(char));
while((c = fgetc(file)) != EOF) {
    char* snew = (char *)realloc(s, count*sizeof(char));
    if(!snew) {
        exit(1);
    }
    s = snew;
    s[count-1] = c;
    count++;
}

或者这样更好:

char c;
int count = 0;
int size = 1;
char* s = malloc(sizeof(char));
while((c = fgetc(file)) != EOF) {
    s[count] = c;
    count++;
    if(count >= size) {
        size*=2;
        char* snew = (char *)realloc(s, size*sizeof(char));
        if(!snew) {
            exit(1);
        }
        s = snew;
    }
}

最佳答案

如今内存充足,因此拥有准确的内存量不如尽量缩短运行时间重要。

第二种方案,即在需要更多内存时将分配的内存加倍,通常被认为是更好的选择。

关于c - 过度使用 realloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51270559/

相关文章:

c - 内部 realloc() 的未定义行为

c - 是否可以在 C 中重载运算符?

C 自动变量和内存地址

C++:XCode EXC_BAD_ACCESS 问题

c++ - 一遍又一遍地重新定义变量是否会增加内存?

c - 如何在 C 函数中返回 `realloc` 数组

c、从头开始shrink分配的空间

c - Gdb 函数入口点未知

c - LVM_GETITEM 困惑

c - 如何以 root 身份仅运行一些 makefile 命令?