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 12:41

int get_input(void) {
  char* input;      
  int c, n, parens; 
  int incr = 500;   

  // get a buffer for storage
  if (!(input = (char*) malloc(incr)))
    return -1;                       
  n = parens = 0;                    

  // read until EOF or newline with balanced parens
  printf("%% ");                                  
  while ((c = getchar()) != EOF) {                
    if (c == '\n' && parens <= 0)                 
      break;                                      
    input[n++] = c;                               

    // handle parens
    if (c == '(')  
      ++parens;    
    else if (c == ')')
      --parens;      

    // grow buffer
    if (n % incr == 0)
      if (!(input = (char*) realloc(input, n + incr)))
        return -1;                                   
  }                                                  

  // done
  input[n] = 0;
  if (c == EOF) printf("\n");
  printf("%s\n", input);    
  free(input);              
  return c == EOF ? -1 : 0; 
}


- pulls out increment as a constant
- returns -1 on failure (you were returning 0 everywhere for some reason)
- checks for end of file (ctrl+d or closed pipe)
- checks for too many closing parens
- adds CODE COMMENTS, so you can actually see what's going on

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