scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | Submodules | README | LICENSE

commit 16eae6287d270bfdfb8e1eff0552605045a5f263
parent de253dbb0bb7b55ced104e574b9527581474234a
Author: Roberto E. Vargas Caballero <k0ga@shike2.com>
Date:   Mon, 15 Oct 2018 13:30:07 +0100

[lib/c] Allocate buffers in stdio by demand

Don't allocate buffers for FILEs before they are used.

Diffstat:
Mlib/c/__getc.c | 8++++++++
Mlib/c/__putc.c | 8++++++++
Mlib/c/_fpopen.c | 9+--------
Mlib/c/stdio.c | 7++-----
4 files changed, 19 insertions(+), 13 deletions(-)

diff --git a/lib/c/__getc.c b/lib/c/__getc.c @@ -22,6 +22,14 @@ __getc(FILE *fp) return EOF; } + if (fp->buf == NULL) { + if ((fp->buf = malloc(BUFSIZ)) == NULL) { + errno = ENOMEM; + return NULL; + } + fp->flags |= _IOALLOC; + } + if ((cnt = _read(fp->fd, fp->buf, fp->len)) <= 0) { fp->flags |= (cnt == 0) ? _IOEOF : _IOERR; return EOF; diff --git a/lib/c/__putc.c b/lib/c/__putc.c @@ -45,6 +45,14 @@ __putc(int ch, FILE *fp) return EOF; } + if (fp->buf == NULL) { + if ((fp->buf = malloc(BUFSIZ)) == NULL) { + errno = ENOMEM; + return NULL; + } + fp->flags |= _IOALLOC; + } + if (first) { if (atexit(cleanup)) { fp->flags |= _IOERR; diff --git a/lib/c/_fpopen.c b/lib/c/_fpopen.c @@ -56,14 +56,7 @@ _fpopen(const char * restrict fname, if ((fd = _open(fname, flags)) < 0) return NULL; - if (fp->buf == NULL) { - if ((fp->buf = malloc(BUFSIZ)) == NULL) { - _close(fd); - errno = ENOMEM; - return NULL; - } - fp->flags |= _IOALLOC; - } + fp->buf = NULL; fp->fd = fd; if (!bin) diff --git a/lib/c/stdio.c b/lib/c/stdio.c @@ -1,12 +1,9 @@ #include <stdio.h> -static unsigned char inbuf[BUFSIZ]; -static unsigned char outbuf[BUFSIZ]; - FILE __iob[FOPEN_MAX] = { { .fd = 0, - .buf = inbuf, + .buf = NULL, .len = BUFSIZ, .flags = _IOREAD, .lp = inbuf, @@ -15,7 +12,7 @@ FILE __iob[FOPEN_MAX] = { }, { .fd = 1, - .buf = outbuf, + .buf = NULL, .len = BUFSIZ, .flags = _IOWRITE | _IOLBF, .lp = outbuf,