C Best way to read series of characters without known length

77 views Asked by At

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;
}
1

There are 1 answers

4
A.N On

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:

#define DEFAULT_STEP_SIZE 64
char* read(void) 
{
    int  count = 0,
         valid = 1,
         num_alloc = 0;
    char *str = NULL,
         *tmp = NULL;
    char input;

    str = malloc(DEFAULT_STEP_SIZE * sizeof(char));
    if(str == NULL){
        return NULL;
    }
    num_alloc = 1;
    printf("Digita sequenza di parentesi da analizzare: ");
    do
    {
        scanf("%c", &input);

        if(count > num_alloc * DEFAULT_STEP_SIZE){
            ++num_alloc;
            tmp = (char *)realloc(str, (num_alloc * DEFAULT_STEP_SIZE) * sizeof(char));
            if(tmp == NULL){
                free(str);
                return NULL;
            }else{
                str = tmp;
            }
        }

        count++; 
        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;

    } while(input != '\n');

    /* TODO */
    /* str[count] = '\0'; */

    return (valid) ? str : NULL;
}