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
[EMAIL PROTECTED]
http://www.math.missouri.edu/~stephen
To Unsubscribe: send mail to [EMAIL PROTECTED]
with "unsubscribe freebsd-hackers" in the body of the message
- Re: malloc Tony Finch
- Re: malloc Terry Lambert
- Re: malloc Tony Finch
- Re: malloc Terry Lambert
- Re: malloc Dan Nelson
- Re: malloc Terry Lambert
- Re: malloc Dan Nelson
- Re: malloc Terry Lambert
- Re: malloc Christoph Hellwig
- Re: malloc Brooks Davis
- Re: malloc Stephen Montgomery-Smith
- Re: malloc Brooks Davis
- Re: malloc Terry Lambert
- Re: malloc David Schultz
- Re: malloc Poul-Henning Kamp
- Re: malloc David Schultz
- Re: malloc Poul-Henning Kamp
- Re: malloc David Schultz
- Re: malloc Poul-Henning Kamp
- Re: malloc Danny Braniss
- Re: malloc Terry Lambert