don't do linear allocations, double allocation request each time. also, remove unneeded casts from MALLOC, etc. Reference: /n/atom/patch/applied/diffmalloclg Date: Mon Sep 28 07:11:51 CES 2015 Signed-off-by: quanstro@quanstro.net --- /sys/src/cmd/diff/diffio.c Mon Sep 28 07:11:02 2015 +++ /sys/src/cmd/diff/diffio.c Mon Sep 28 07:11:03 2015 @@ -124,7 +124,7 @@ prepare(int i, char *arg) { struct line *p; - int j, h; + int j, h, a; Biobuf *bp; char *cp, buf[MAXLINELEN]; int nbytes; @@ -153,9 +153,16 @@ } Bseek(bp, 0, 0); } - p = MALLOC(struct line, 3); - for (j = 0; h = readhash(bp, buf); p[j].value = h) - p = REALLOC(p, struct line, (++j+3)); + a = 1; + p = MALLOC(struct line, a+3); + for (j = 0; h = readhash(bp, buf); p[j].value = h){ + if(j > a){ + a = j<<1; + p = REALLOC(p, struct line, a+3); + } + j++; + } + len[i] = j; file[i] = p; input[i] = bp; /*fix*/ --- /sys/src/cmd/diff/diffdir.c Mon Sep 28 07:11:05 2015 +++ /sys/src/cmd/diff/diffdir.c Mon Sep 28 07:11:06 2015 @@ -19,18 +19,13 @@ int nitems; int fd, n; - if ((fd = open(name, OREAD)) < 0) { + if ((fd = open(name, OREAD)) < 0) fprint(2, "%s: can't open %s: %r\n", argv0, name); - /* fake an empty directory */ - cp = MALLOC(char*, 1); - cp[0] = 0; - return cp; - } cp = 0; nitems = 0; if((n = dirreadall(fd, &db)) > 0){ + cp = MALLOC(char*, n+1); while (n--) { - cp = REALLOC(cp, char *, (nitems+1)); cp[nitems] = MALLOC(char, strlen((db+n)->name)+1); strcpy(cp[nitems], (db+n)->name); nitems++; --- /sys/src/cmd/diff/diff.h Mon Sep 28 07:11:08 2015 +++ /sys/src/cmd/diff/diff.h Mon Sep 28 07:11:09 2015 @@ -7,9 +7,9 @@ extern Biobuf stdout; extern int binary; -#define MALLOC(t, n) ((t *)emalloc((n)*sizeof(t))) -#define REALLOC(p, t, n) ((t *)erealloc((void *)(p), (n)*sizeof(t))) -#define FREE(p) free((void *)(p)) +#define MALLOC(t, n) (emalloc((n)*sizeof(t))) +#define REALLOC(p, t, n) (erealloc((void *)(p), (n)*sizeof(t))) +#define FREE(p) free(p) #define MAXPATHLEN 1024