When reading in data to a string, is it better to use as many realloc
's as necessary to get the correct amount of memory, or is it better to use less realloc
's but potentially end up with unused memory?
For instance, is this better:
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++;
}
Or is this better:
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;
}
}
Memory is abundant these days, so having an exact amount of memory isn't quite as important as minimizing your run time.
The second scheme, where you double the allocated memory anytime you need more, is generally considered the better option.