Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Teach me to remove bloat!

Name: Anonymous 2010-02-24 0:34

Hey guys, I would like some pointer (no, not that kind) on removing bloat in code. Here is a fully functional piece of code that I wrote which I'm worried about bloat in. How do I shorten this?

int get_input()
{
    int count, paren_count, total_count, c;
    char *input, *temp;

    input = (char *) malloc (500 * sizeof (char));

    if (input == NULL) return 0;
    printf("%% ");
    for (count = paren_count = total_count = 0; (c = getchar()) != EOF; count++, input++, total_count++)
    {
        if (count == 499)
        {
            input -= total_count;
            temp = (char *) realloc (input, (500 + total_count) * sizeof (char));
            if (temp == NULL)
                return 0;
            input = temp;
            input += total_count;
        }
        if (c == '\n')
        {
            *input = '\0';
            temp = input;
            temp -= (count);
            count = 0;
            for (; *temp != '\0'; temp++)
            {
                if (*temp == '(')
                    paren_count++;
                else if (*temp == ')')
                    paren_count--;
            }
            if (paren_count == 0)
                break;
            printf("  ");
        }
        *input = c;
    }
    *temp = '\0';
    input -= total_count;
    printf("%s\n", input);
    free(input);
    return 0;
}

Name: Anonymous 2010-02-24 19:50

>>39
I hate higher level languages in general (save for languages like scheme and perl), plus the linked lists are so much easier in C. And you're right, worrying about efficiency in the beginning is stupid, I was just saying how safety is necessary for what I'm doing.

Any way, here's my fixed version. Sorry if I don't get the bbcode right

int get_input()
{
    int count, post_count;
    char *input = NULL, *temp, c;

    printf("%% ");
    for (count = 0; (c = getchar()) != EOF; count++)
    {
        if (count % 500 == 0)
        {
            if ((temp = (char *) realloc (input, (500 + count) * sizeof (char))) == NULL)
            {
                free (input);
                return 2;
            }
            input = temp;
        }
        input[count] = c;
        if (c == '\n')
        {
            input[count + 1] = '\0';
            temp = input;
            post_count = 0;
            while (*temp != '\0')
            {
                if (*temp == '(')
                    post_count++;
                else if (*temp == ')')
                    post_count--;
                temp++;
            }
            if (post_count > 0)
                printf("  ");
            else
                break;
        }

    }
    printf("%s\n", input);
    free(input);
    return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List