将数据读入字符串时,使用尽可能多的 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/