Add custom memory allocation
[jansson.git] / test / suites / api / test_memory_funcs.c
1 #include <string.h>
2 #include <jansson.h>
3
4 #include "util.h"
5
6 static int malloc_called = 0;
7 static int free_called = 0;
8
9 /* helper */
10 static void create_and_free_complex_object()
11 {
12     json_t *obj;
13
14     obj = json_pack("{s:i,s:n,s:b,s:b,s:{s:s},s:[i,i,i]",
15                     "foo", 42,
16                     "bar",
17                     "baz", 1,
18                     "qux", 0,
19                     "alice", "bar", "baz",
20                     "bob", 9, 8, 7);
21
22     json_decref(obj);
23 }
24
25 static void *my_malloc(size_t size)
26 {
27     malloc_called += 1;
28     return malloc(size);
29 }
30
31 static void my_free(void *ptr)
32 {
33     free_called += 1;
34     free(ptr);
35 }
36
37 static void test_simple()
38 {
39     json_set_alloc_funcs(my_malloc, my_free);
40     create_and_free_complex_object();
41
42     if(malloc_called != 27 || free_called != 27)
43         fail("Custom allocation failed");
44 }
45
46
47 /*
48   Test the secure memory functions code given in the API reference
49   documentation, but by using plain memset instead of
50   guaranteed_memset().
51 */
52
53 static void *secure_malloc(size_t size)
54 {
55     /* Store the memory area size in the beginning of the block */
56     void *ptr = malloc(size + 8);
57     *((size_t *)ptr) = size;
58     return ptr + 8;
59 }
60
61 static void secure_free(void *ptr)
62 {
63     size_t size;
64
65     ptr -= 8;
66     size = *((size_t *)ptr);
67
68     /*guaranteed_*/memset(ptr, 0, size);
69     free(ptr);
70 }
71
72 static void test_secure_funcs(void)
73 {
74     json_set_alloc_funcs(secure_malloc, secure_free);
75     create_and_free_complex_object();
76 }
77
78 int main()
79 {
80     test_simple();
81     test_secure_funcs();
82
83     return 0;
84 }