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
的比较非常重要。只需将文件映射到内存中即可。