Skip to content
This repository has been archived by the owner on Dec 21, 2021. It is now read-only.

Commit

Permalink
Reduced number of calls to realloc() when loading from stdin
Browse files Browse the repository at this point in the history
  • Loading branch information
Gregungory committed Feb 21, 2014
1 parent bd0949e commit 9d51bbe
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/util/rcollate.c
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#ifndef lint
static const char RCSid[] = "$Id: rcollate.c,v 2.7 2013/11/18 22:02:12 greg Exp $";
static const char RCSid[] = "$Id: rcollate.c,v 2.8 2014/02/21 13:49:00 greg Exp $";
#endif
/*
* Utility to re-order records in a binary or ASCII data file (matrix)
Expand Down Expand Up @@ -103,6 +103,7 @@ load_file(MEMLOAD *mp, FILE *fp)
static int
load_stream(MEMLOAD *mp, FILE *fp)
{
size_t alloced = 0;
char buf[8192];
size_t nr;

Expand All @@ -114,10 +115,11 @@ load_stream(MEMLOAD *mp, FILE *fp)
if (fp == NULL)
return(-1);
while ((nr = fread(buf, 1, sizeof(buf), fp)) > 0) {
if (!mp->len)
if (!alloced)
mp->base = malloc(nr);
else
mp->base = realloc(mp->base, mp->len+nr);
else if (mp->len+nr > alloced)
mp->base = realloc(mp->base,
alloced = alloced*(2+(nr==sizeof(buf)))/2+nr);
if (mp->base == NULL)
return(-1);
memcpy((char *)mp->base + mp->len, buf, nr);
Expand All @@ -127,6 +129,8 @@ load_stream(MEMLOAD *mp, FILE *fp)
free_load(mp);
return(-1);
}
if (alloced > mp->len*5/4) /* don't waste too much space */
mp->base = realloc(mp->base, mp->len);
return(mp->len > 0);
}

Expand Down

0 comments on commit 9d51bbe

Please sign in to comment.