/src/jansson-2.14/src/memory.c
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org> |
3 | | * Copyright (c) 2011-2012 Basile Starynkevitch <basile@starynkevitch.net> |
4 | | * |
5 | | * Jansson is free software; you can redistribute it and/or modify it |
6 | | * under the terms of the MIT license. See LICENSE for details. |
7 | | */ |
8 | | |
9 | | #include <stdlib.h> |
10 | | #include <string.h> |
11 | | |
12 | | #include "jansson.h" |
13 | | #include "jansson_private.h" |
14 | | |
15 | | /* C89 allows these to be macros */ |
16 | | #undef malloc |
17 | | #undef free |
18 | | |
19 | | /* memory function pointers */ |
20 | | static json_malloc_t do_malloc = malloc; |
21 | | static json_free_t do_free = free; |
22 | | |
23 | 0 | void *jsonp_malloc(size_t size) { |
24 | 0 | if (!size) |
25 | 0 | return NULL; |
26 | | |
27 | 0 | return (*do_malloc)(size); |
28 | 0 | } |
29 | | |
30 | 0 | void jsonp_free(void *ptr) { |
31 | 0 | if (!ptr) |
32 | 0 | return; |
33 | | |
34 | 0 | (*do_free)(ptr); |
35 | 0 | } |
36 | | |
37 | 0 | char *jsonp_strdup(const char *str) { return jsonp_strndup(str, strlen(str)); } |
38 | | |
39 | 0 | char *jsonp_strndup(const char *str, size_t len) { |
40 | 0 | char *new_str; |
41 | |
|
42 | 0 | new_str = jsonp_malloc(len + 1); |
43 | 0 | if (!new_str) |
44 | 0 | return NULL; |
45 | | |
46 | 0 | memcpy(new_str, str, len); |
47 | 0 | new_str[len] = '\0'; |
48 | 0 | return new_str; |
49 | 0 | } |
50 | | |
51 | 0 | void json_set_alloc_funcs(json_malloc_t malloc_fn, json_free_t free_fn) { |
52 | 0 | do_malloc = malloc_fn; |
53 | 0 | do_free = free_fn; |
54 | 0 | } |
55 | | |
56 | 0 | void json_get_alloc_funcs(json_malloc_t *malloc_fn, json_free_t *free_fn) { |
57 | 0 | if (malloc_fn) |
58 | 0 | *malloc_fn = do_malloc; |
59 | 0 | if (free_fn) |
60 | 0 | *free_fn = do_free; |
61 | 0 | } |