I know there is a common strategy in C to handle the situation that the input data, for example, text, exceed the original allocated space. That is reallocating with more space.
#include <stdlib.h>
#include <stdio.h>
#define BUF_SIZE 1024
void check_buffer(char *buffer)
{
if (!buffer) {
fprintf(stderr, "lsh: allocation error\n");
exit(EXIT_FAILURE);
}
}
char *read_line()
{
int bufsize = BUF_SIZE;
int position = 0;
char *buffer = malloc(sizeof(char) * bufsize);
int c;
check_buffer(buffer);
while (1) {
c = getchar();
if (c == EOF || c == '\n') {
buffer[position] = '\0';
return buffer;
} else {
buffer[position] = c;
}
position++;
if (position >= bufsize) {
bufsize += BUF_SIZE; // Or `bufsize *= 2;`?
buffer = realloc(buffer, bufsize);
check_buffer(buffer);
}
}
}
So what is the better way to expand the original space? bufsize += BUF_SIZE
or bufsize *= 2
? Which way is more effective?