Date: Tue, 22 Oct 2002 13:52:34 -0500 From: Stephen Montgomery-Smith <stephen@math.missouri.edu> To: Brooks Davis <brooks@one-eyed-alien.net> Cc: Terry Lambert <tlambert2@mindspring.com>, Danny Braniss <danny@cs.huji.ac.il>, Poul-Henning Kamp <phk@critter.freebsd.dk>, freebsd-hackers@FreeBSD.ORG Subject: Re: malloc Message-ID: <3DB59E72.2080305@math.missouri.edu> In-Reply-To: <E183u5Y-0003Yc-00@cse.cs.huji.ac.il> References: <E183u5Y-0003Yc-00@cse.cs.huji.ac.il> <3DB50A5A.F87EDA78@mindspring.com> <20021022110159.A1513@Odin.AC.HMC.Edu>
next in thread | previous in thread | raw e-mail | index | archive | help
Brooks Davis wrote:
>
> The user may also see a performance gain on Linux if they use a less
> stupid allocation scheme. I ran into some code once that read strings
> one character at a time via getc() and did a realloc for each read.
> Needless to say, performance was truly awful since a typical run
> required parsing over 600MB of text. I saw a better then 50% speedup on
> Alpha Linux when I fixed that mess.
>
> -- Brooks
>
As an amateur programmer, I wrote a program something like this. But it
allocates memory 1000 bytes at a time in order to save some of this
overhead. I would be interested in getting feedback about this little
function I wrote as to whether it could be greatly improved. (It works
great for me, but probably I haven't really pushed it very hard.)
#include <stdio.h>
#include <stdlib.h>
/* Get a string from the stream f, allocating space to s as required.
*/
char *fgetsalloc(char **s, FILE *f) {
int c;
int len;
int allocated;
allocated = 1000;
if ((*s = realloc(*s,1000))==NULL) {
fprintf(stderr,"Allocation error\n");
exit(1);
}
len = 0;
while (1) {
c=getc(f);
if (c==EOF) break;
if (len>=allocated-1) {
allocated += 1000;
if ((*s = realloc(*s,allocated))==NULL) {
fprintf(stderr,"Allocation error\n");
exit(1);
}
}
(*s)[len] = c;
len++;
if (c=='\n') break;
}
if (len!=0) {
(*s)[len] = '\0';
if ((*s = realloc(*s,len+1))==NULL) {
fprintf(stderr,"Allocation error\n");
exit(1);
}
}
else {
if (*s!=NULL) free(*s);
*s = NULL;
}
return *s;
}
--
Stephen Montgomery-Smith
stephen@math.missouri.edu
http://www.math.missouri.edu/~stephen
To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?3DB59E72.2080305>
