CODE: fread_string()

From: Peter Finlayson (frnknstn@iafrica.com)
Date: 04/22/02


I have a question about the fread_string() function:

This code declares:
char* point;
char tmp[512];

and then reads 512 bytes from a file into 'tmp'.  It then (if it
doesn't find a '~' in tmp) proceeds to:

      point = tmp + strlen(tmp) - 1;
      *(point++) = '\r';
      *(point++) = '\n';
      *point = '\0';

If the line read was longer than 512 bytes, this can cause the program
to crash.  At the very least, the first line should read
      point = tmp + strlen(tmp) - 3;
 so there is enough room for the "\r\n\0", but perhaps they should just
read one less bytes into 'tmp' (to make sure there is always room for
expansion) and only actualy do the expansion if a newline was read:

char *fread_string(FILE *fl, const char *error)
{
  char buf[MAX_STRING_LENGTH], tmp[512];
  char *point;
  int done = 0, length = 0, templength;

  *buf = '\0';

  do {
    if (!fgets(tmp, 511, fl)) {
      log("SYSERR: fread_string: format error at or near %s", error);
      exit(1);
    }
    /* If there is a '~', end the string; else put a "\r\n" over the
'\n'. */
    if ((point = strchr(tmp, '~')) != NULL) {
      *point = '\0';
      done = 1;
    } else if (*(point = tmp + strlen(tmp) - 1) == '\n') {
      *(point++) = '\r';
      *(point++) = '\n';
      *point = '\0';
    }

    templength = strlen(tmp);

    if (length + templength >= MAX_STRING_LENGTH) {
      log("SYSERR: fread_string: string too large (db.c)");
      log("%s", error);
      exit(1);
    } else {
      strcat(buf + length, tmp);        /* strcat: OK (size checked above) */
      length += templength;
    }
  } while (!done);

  /* allocate space for the new string and copy it */
  return (strlen(buf) ? strdup(buf) : NULL);
}

Comments?
Peter Finlayson
frnknstn@iafrica.com

--
   +---------------------------------------------------------------+
   | FAQ: http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html |
   | Archives: http://post.queensu.ca/listserv/wwwarch/circle.html |
   | Newbie List:  http://groups.yahoo.com/group/circle-newbies/   |
   +---------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 06/25/03 PDT