ぼるじょあがC/C++の宿題を片づけますYO! 20代目

このエントリーをはてなブックマークに追加
いっそのこと可変長にしてしまえ。

char *getline()
{
  char *buf, *p;
  int c, used = 0, lim = 2;

  if ( (buf = malloc(lim)) == NULL)
    return NULL;

  while ( (c = getchar()) != EOF && c != '\n') {
    if (used >= lim-1) {
      lim *= 2;
      if ( (p = realloc(buf, lim)) == NULL) {
        free(buf);
        return NULL;
      }
      buf = p;
    }
    buf[used++] = c;
  }
  buf[used] = '\0';

  return buf;
}