commit 3c7144d5d343692883589bedf327c4e3244d9f29
parent e09ad0442d5af5784989e81a81b390bed5295d13
Author: Roberto E. Vargas Caballero <k0ga@shike2.com>
Date: Fri, 29 Jun 2012 13:43:46 +0200
Added wrapper.c
This module has all the wrappers about usual system functions like malloc or
strdup, doing that caller can be sure that returned value is correct.
Diffstat:
5 files changed, 42 insertions(+), 6 deletions(-)
diff --git a/Makefile b/Makefile
@@ -1,5 +1,6 @@
-OBJS = types.o decl.o lex.o error.o symbol.o flow.o main.o expr.o keyword.o code.o
+OBJS = types.o decl.o lex.o error.o symbol.o flow.o main.o expr.o keyword.o \
+ code.o wrapper.o
LIBS =
all: kcc
diff --git a/cc.h b/cc.h
@@ -20,4 +20,7 @@ extern void warning(const char *fmt, ...);
extern void error(const char *fmt, ...);
extern void die(const char *fmt, ...);
extern void warning_error(char flag, const char *fmt, ...);
+extern void *xmalloc(size_t size);
+extern void *xcalloc(size_t nmemb, size_t size);
+extern char *xstrdup(const char *s);
#endif
diff --git a/symbol.c b/symbol.c
@@ -5,8 +5,6 @@
#include "cc.h"
#include "symbol.h"
-#define xmalloc malloc
-#define xstrdup strdup
#define NR_SYM_HASH 32
struct symhash {
diff --git a/types.c b/types.c
@@ -7,9 +7,6 @@
#include "tokens.h"
#include "symbol.h"
-/* TODO: create wrapper file */
-#define xcalloc calloc
-
struct type tschar = {.btype = CHAR};
struct type tshort = {.btype = SHORT};
struct type tint = {.btype = INT};
diff --git a/wrapper.c b/wrapper.c
@@ -0,0 +1,37 @@
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "cc.h"
+
+
+static void out_of_memory(void)
+{
+ /* TODO: deal with out of memory errors */
+ error("out of memory");
+}
+
+void *xmalloc(size_t size)
+{
+ register void *p = malloc(size);
+
+ if (!p)
+ out_of_memory();
+ return p;
+}
+
+void *xcalloc(size_t nmemb, size_t size)
+{
+ register size_t nbytes = nmemb * size;
+ register void *p = xmalloc(nbytes);
+
+ return memset(p, nbytes, 0);
+}
+
+char *xstrdup(const char *s)
+{
+ register size_t len = strlen(s);
+ register char *p = xmalloc(len);
+
+ return memcpy(p, s, len);
+}