iris

small scheme interpreter
git clone git://git.2f30.org/iris
Log | Files | Refs | LICENSE

commit 4c4a42433bc8cff7f099381d0375e58d59973cca
parent 986bacd157cbd9c1e8965c66d2576da04968367b
Author: sin <sin@2f30.org>
Date:   Wed, 14 May 2014 16:22:17 +0100

Add wrappers for memory allocation

Diffstat:
MMakefile | 2+-
Mparser.c | 35+++++------------------------------
Mutil.c | 46+++++++++++++++++++++++++++++++---------------
Mutil.h | 4+++-
4 files changed, 40 insertions(+), 47 deletions(-)

diff --git a/Makefile b/Makefile @@ -5,7 +5,7 @@ OBJ = ${SRC:.c=.o} CC = cc -CFLAGS = -Wall -Wextra -g +CFLAGS = -Wall -Wextra -Wno-switch -g LDFLAGS = $(BIN): ${OBJ} diff --git a/parser.c b/parser.c @@ -5,37 +5,12 @@ #include <string.h> #include "lexer.h" #include "parser.h" +#include "util.h" static struct object * newobject(void) { - struct object *o; - - o = calloc(1, sizeof(*o)); - if (!o) { - perror("calloc"); - exit(EXIT_FAILURE); - } - return o; -} - -static struct object * -freeobject(struct object *o) -{ - if (!o) - return; - switch (o->type) { - case OError: - free(o->d.err.s); - break; - case OEof: - free(o->d.eof.s); - break; - case OString: - free(o->d.s.s); - break; - } - free(o); + return ecalloc(1, sizeof(struct object)); } static struct object * @@ -49,7 +24,7 @@ error(struct tok *t) return NULL; o = newobject(); o->type = OError; - o->d.err.s = strdup(l); + o->d.err.s = estrdup(l); free(l); return o; } @@ -65,7 +40,7 @@ eof(struct tok *t) return NULL; o = newobject(); o->type = OEof; - o->d.eof.s = strdup(l); + o->d.eof.s = estrdup(l); free(l); return o; } @@ -132,7 +107,7 @@ string(struct tok *t) return NULL; o = newobject(); o->type = OString; - o->d.s.s = strdup(l); + o->d.s.s = estrdup(l); free(l); return o; } diff --git a/util.c b/util.c @@ -3,25 +3,41 @@ #include <stdlib.h> #include <string.h> -char * -afgets(char **p, size_t *size, FILE *fp) +void * +ecalloc(size_t nmemb, size_t size) { - char buf[BUFSIZ]; - size_t n, len = 0; + void *p; - while(fgets(buf, sizeof buf, fp)) { - len += (n = strlen(buf)); - if(len + 1 > *size && !(*p = realloc(*p, len + 1))) { - perror("realloc"); - exit(EXIT_FAILURE); - } + p = calloc(nmemb, size); + if (!p) { + perror("calloc"); + exit(EXIT_FAILURE); + } + return p; +} - memcpy(&(*p)[len - n], buf, n); - (*p)[len] = '\0'; +void * +emalloc(size_t size) +{ + void *p; - if(buf[n - 1] == '\n' || feof(fp)) - break; + p = malloc(size); + if (!p) { + perror("malloc"); + exit(EXIT_FAILURE); } + return p; +} - return (len > 0) ? *p : NULL; +char * +estrdup(const char *s) +{ + char *r; + + r = strdup(s); + if (!r) { + perror("strdup"); + exit(EXIT_FAILURE); + } + return r; } diff --git a/util.h b/util.h @@ -1,4 +1,6 @@ /* See LICENSE file for copyright and license details. */ #define LEN(x) (sizeof (x) / sizeof *(x)) -char *afgets(char **, size_t *, FILE *); +void *ecalloc(size_t, size_t); +void *emalloc(size_t); +char *estrdup(const char *);