[ create a new paste ] login | about

Link: http://codepad.org/vNntsDwe    [ raw code | output | fork ]

C, pasted on Jul 27:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

/* ------------------------- */
#define BUFFSIZE 3 /* >= 2 */
char *getline(void)
{
  static char inbuff[BUFFSIZE];
  char *outbuff_malloc, *tmpbuff;
  char *p;
  int fEOL;

  if ((outbuff_malloc = malloc(1)) == NULL)
    return NULL;
  *outbuff_malloc = '\0';
  fEOL = 0;
  do {
    if (fgets(inbuff, BUFFSIZE, stdin) == NULL)
      break;
    for (p = inbuff; *p != '\0'; p++)
      ;
    if (*(p - 1) == '\n') {
      *(p - 1) = '\0';
      fEOL = 1;
    }
    if ((tmpbuff = realloc(outbuff_malloc, strlen(outbuff_malloc) + strlen(inbuff) + 1)) ==NULL) {
      free(outbuff_malloc);
      return NULL;
    }
    strcat(tmpbuff, inbuff);
    outbuff_malloc = tmpbuff;
  } while (!fEOL);
  return outbuff_malloc;
}

struct slist{
  char *name;
  int score;
  struct slist *next;
};

void printlist(struct slist *s);
int add(struct slist **input, char *str, int x);
void allfree(struct slist *s);

int main() {
  struct slist *a = NULL;
  char *buf, *p, *name, *q;
  int i;
  while(1){
    printf(">> ");
    buf = getline();
    for (p = buf; isalpha(*p); p++)
      ;
    *p = '\0';
    if ((name = malloc(sizeof(char) * (strlen(buf) + 1))) == NULL) {
      fprintf(stderr, "cannot allocate enough memroy.\n");
      exit(-1);
    }
    strcpy(name, buf);
    p++;
    for (q = p; isdigit(*q); q++)
      ;
    *q = '\0';
    i = atoi(p);
    if (strcmp(name, "end") == 0 && i == 0) {
      free(buf);
      free(name);
      break;
    }
    if (add(&a, name, i) != 0) {
      fprintf(stderr, "cannot allocate enough memory.\n");
      exit(-1);
    }
    free(buf);
    printlist(a);
  }
  allfree(a);
  return 0;
}

void printlist(struct slist *s){
  if(s == NULL){
    printf("\n");
  } else {
    printf("%s(%d) ", s->name, s->score);
    printlist(s->next);
  }
}

int add(struct slist **input, char *str, int x) {
  struct slist *output;
  int c;
  if(*input == NULL) {
    if ((output = malloc(sizeof(struct slist))) == NULL)
      return -1;
    output->name = str;
    output->score = x;
    output->next = NULL;
    *input = output;
    return 0;
  } else {
    c = strcmp((*input)->name, str);
    if (c == 0) {
      (*input)->score = x;
      free(str);
      return 0;
    } else if (c > 0) {
      if ((output = malloc(sizeof(struct slist))) == NULL)
        return -1;
      output->name = str;
      output->score = x;
      output->next = *input;
      *input = output;
      return 0;
    } else {
      return add(&((*input)->next), str, x);
    }
  }
}

void allfree(struct slist *s) {
  struct slist *p;
  if (s != NULL) {
    free(s->name);
    p = s->next;
    free(s);
    allfree(p);
  }
}
/* end */


Output:
1
2
3
memory clobbered past end of allocated block

Exited: ExitFailure 127


Create a new paste based on this one


Comments: