I've to read a series of characters that must be brackets but I don't know how many characters the user type. So I think to use realloc
each time I've to add the input.
I have to use scanf
to read the characters
I wrote this code that works but I want to know if there's a way more secure or simply better.
char* read(void)
{
int count = 0,
valid = 1;
char *str = NULL,
*tmp = NULL;
char input;
printf("Digita sequenza di parentesi da analizzare: ");
do
{
scanf("%c", &input);
tmp = (char *)realloc(str, (++count) * sizeof(char));
if(tmp != NULL)
{
str = tmp;
str[count-1] = input;
/* check sul carattere letto verificando che sia una parentesi (escluso ENTER) */
if((input != '(' &&
input != ')' &&
input != '[' &&
input != ']' &&
input != '{' &&
input != '}' &&
input != '\n') ||
((count == 1) &&
(input == '\n')))
valid = 0;
}
else
{
valid = 0;
free(str);
}
} while(input != '\n');
/* TODO */
/* str[count] = '\0'; */
return (valid) ? str : NULL;
}
I would not suggest doing a realloc at every iteration. Rather use some optimal size buffer at the beginning and then do a realloc only if this size is crossed. Something as below: