commit 66c4f93d1ac76872da2ef44eb0d36c26a610aa32
parent 36ba40797440913bbaa18d034979d19af373f1f7
Author: gearsix <gearsix@tuta.io>
Date: Thu, 16 Dec 2021 12:17:03 +0000
added stdlib wrapper to test
Diffstat:
3 files changed, 55 insertions(+), 4 deletions(-)
diff --git a/Makefile b/Makefile
@@ -10,7 +10,7 @@ all:
test:
rm -f test
- ${CC} -Wall -pedantic -g -o test test.c tralloc.c
+ ${CC} -Wall -pedantic -g -DTRALLOC_WRAP -o test test.c tralloc.c
@./test
clean:
diff --git a/README.md b/README.md
@@ -1,5 +1,5 @@
-# tralloc
+# tralloc - track allocations
An ANSI-C libray for tracking heap-allocated memory.
@@ -43,6 +43,8 @@ segfault.
tralloc functions.
- You should be able to use the _tralloc stdlib wrappers_ just as you
would use their stdlib counterparts without error.
+- If you want to use `malloc` instead of `tr_malloc`, use a macro.
+See `test.c` for an example of this.
## API
diff --git a/test.c b/test.c
@@ -14,6 +14,22 @@ int main (int argc, char *argv[])
size_t siz;
char *str;
+#ifdef TRALLOC_WRAP /* example of how to replace stdlib functions */
+ #define malloc(n) tr_malloc(n)
+ #define calloc(num, n) tr_calloc(num, n)
+ #define realloc(ptr, n) tr_realloc(ptr, n)
+ #define free(ptr) tr_free(ptr)
+
+ test_tralloc_wrap (); /* calls malloc, calloc, realloc, free */
+#else
+ test_tralloc();
+#endif
+
+ return EXIT_SUCCESS;
+}
+
+void test_tralloc()
+{
printf("tr_siz: %lu, tr_limit: %lu\n", tr_siz(), tr_limit());
if (tr_siz() != 0) fail("initial tr_siz not 0\n");
if (tr_limit() != 0) fail("initial tr_setlimit not 0\n");
@@ -45,7 +61,40 @@ int main (int argc, char *argv[])
str = tr_calloc(2, siz); /* should cause assertion failure */
printf("str = '%s', %zu bytes\n", str, tr_allocsiz(str));
tr_free(str);
-
+}
- return EXIT_SUCCESS;
+void test_tralloc_wrap()
+{
+ printf("tr_siz: %lu, tr_limit: %lu\n", tr_siz(), tr_limit());
+ if (tr_siz() != 0) fail("initial tr_siz not 0\n");
+ if (tr_limit() != 0) fail("initial tr_setlimit not 0\n");
+
+ siz = 6;
+ str = malloc(siz);
+ printf("str = '%s', %zu bytes\n", str, tr_allocsiz(str));
+ if (str == NULL) fail("malloc failed\n");
+ if (tr_allocsiz(str) != (siz + sizeof(size_t))) fail("invalid tr_allocsiz value\n");
+ strcpy(str, "foobar");
+ if (strcmp(str, "foobar") != 0) fail("strcpy failed\n");
+ printf("str = '%s', %zu bytes\n", str, tr_allocsiz(str));
+
+ siz = 12;
+ str = realloc(str, siz);
+ printf("str = '%s', %zu bytes\n", str, tr_allocsiz(str));
+ if (str == NULL) fail("realloc failed\n");
+ if (tr_allocsiz(str) != (siz + sizeof(size_t))) fail("invalid tr_allocsiz value\n");
+ strcpy(str, "foobarfoobar");
+ if (strcmp(str, "foobarfoobar") != 0) fail("strcpy failed\n");
+ printf("str = '%s', %zu bytes\n", str, tr_allocsiz(str));
+
+ free(str);
+
+ siz = 6;
+ tr_setlimit(10);
+ puts("the following should cause an assertion failure:");
+ fflush(stdout);
+ str = calloc(2, siz); /* should cause assertion failure */
+ printf("str = '%s', %zu bytes\n", str, tr_allocsiz(str));
+ free(str);
}
+