test_memory_funcs.c 1.5 KB

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