M
Michael Brennan
And fgets() is in practise too difficult for any but the best programmers to
use safely.
That certainly means I am unable to use fgets() safely,
and since I just wrote this function which reads from stdin
using fgets() I thought I would to like to hear any opinions
on my code from the people here.
Although it may not be the best way to handle memory, I'm
mostly interested to know if this code is correct, and safe.
Thanks!
/Michael Brennan
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSZ 128
char *readstr(void)
{
char buffer[BUFSZ];
char *input;
size_t size;
char *tmp;
input = NULL;
size = 0;
do {
tmp = realloc(input, size + BUFSZ);
if (tmp == NULL) {
free(input);
return NULL;
}
input = tmp;
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
free(input);
return NULL;
}
if (size == 0)
strcpy(input, buffer);
else
strcat(input, buffer);
size = strlen(input);
} while (strrchr(buffer, '\n') == NULL);
input[strcspn(input, "\n")] = '\0';
return input;
}