I'm trying to dynamically allocate an array to read user input from the command line. It works 99/100 times, but if I type in a bunch of characters repeatedly I will sometimes get a segmentation fault error OR a double free or corruption(fasttop) error. This error is relatively hard to reproduce.
I'm pretty sure the error occurs because of the way I'm reallocating the array.
while(1){
char *buf_in; // Holds user keyboard input
int cnt = 0, length = 0; // cnt stores current read buffer size, length allows input into buf_in
char ch;
int buf_max = 64; // Current buffer size. Dynamically allocated
buf_in = malloc(buf_max * sizeof(char));
if (buf_in==NULL){
fprintf(stderr,"Error allocating memory!\n");
exit(EXIT_FAILURE);
}
do{
if (cnt > (buf_max/2)){
cnt = 0;
buf_max *= 2; // Double size of buffer
printf("Doubling buffer: %d\n",buf_max);
buf_in = realloc(buf_in,buf_max);
if (buf_in == NULL){
fprintf(stderr,"Error re-allocating memory!\n");
exit(EXIT_FAILURE);
}
}
/* Store line-by-line into buffer */
ch = getc(stdin);
buf_in[length] = ch;
length++;
cnt++;
}while(ch != '\n');
/* Handles different option arguments */
processOptions(buf_in,&opt_n_inc);
// stdout
fprintf(stdout,"%s",buf_in);
fflush(stdout);
free(buf_in);
buf_in=NULL;
}