Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
realloc的过度使用_C_Memory Management_Realloc - Fatal编程技术网

realloc的过度使用

realloc的过度使用,c,memory-management,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) { exi

将数据读入字符串时,最好使用尽可能多的
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;
    }
}
还是这样更好:

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;
    }
}

现在内存非常丰富,所以拥有准确的内存量并不像最小化运行时间那么重要


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

现在内存非常丰富,因此拥有准确的内存量并不像最小化运行时间那么重要

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

如果有无约束的行长度,则后者绝对更好,因为构建长度为
n
的字符串所花费的时间将是
O(n)
,而前者是
O(n²)
由于不必要的复制。如果您想减少过度分配,您可以权衡更高的常数因子-例如,始终将缓冲区增加20%1个字符


另外,在
char
未签名的平台上,内存量是不够的…

如果您有无约束的行长度,则后者绝对更好,因为构建长度
n
的字符串所花费的时间将是
O(n)
,而前者是
O(n²)
由于不必要的复制。如果您想减少过度分配,您可以权衡更高的常数因子-例如,始终将缓冲区增加20%1个字符



否则,在一个平台上内存不足,而代码< char > /c>是未签名的……/p>这是C++问题吗?如果是这样,那么最好(通常)让std::string为您处理内存分配。这取决于具体情况。对于您的用例,请同时尝试和meassure(并尝试多次以获得平均值,并使用优化的代码)。始终存在权衡,什么更重要/更受限制?速度还是内存?另一方面,别忘了返回一个
int
。这对于代码< EOF比较非常重要。只需将文件映射到内存。这真的是C++问题吗?如果是这样,那么最好(通常)让std::string为您处理内存分配。这取决于具体情况。对于您的用例,请同时尝试和meassure(并尝试多次以获得平均值,并使用优化的代码)。始终存在权衡,什么更重要/更受限制?速度还是内存?另一方面,别忘了返回一个
int
。这对于与
EOF
的比较非常重要。只需将文件映射到内存中即可。