OpenVPN
test_alloc.c
Go to the documentation of this file.
1 #include "config.h"
2 
3 #include <stdarg.h>
4 #include <stddef.h>
5 #include <setjmp.h>
6 #include <cmocka.h>
7 #include <cmocka_private.h>
8 
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <string.h>
12 
13 static void torture_test_malloc(void **state)
14 {
15  char *str;
16  size_t str_len;
17  size_t len;
18 
19  (void)state; /* unsused */
20 
21  str_len = 12;
22  str = (char *)test_malloc(str_len);
23  assert_non_null(str);
24 
25  len = snprintf(str, str_len, "test string");
26  assert_int_equal(len, 11);
27 
28  len = strlen(str);
29  assert_int_equal(len, 11);
30 
31  test_free(str);
32 }
33 
34 static void torture_test_realloc(void **state)
35 {
36  char *str;
37  char *tmp;
38  size_t str_len;
39  size_t len;
40 
41  (void)state; /* unsused */
42 
43  str_len = 16;
44  str = (char *)test_malloc(str_len);
45  assert_non_null(str);
46 
47  len = snprintf(str, str_len, "test string 123");
48  assert_int_equal(len, 15);
49 
50  len = strlen(str);
51  assert_int_equal(len, 15);
52 
53  str_len = 20;
54  tmp = test_realloc(str, str_len);
55  assert_non_null(tmp);
56 
57  str = tmp;
58  len = strlen(str);
59  assert_string_equal(tmp, "test string 123");
60 
61  snprintf(str + len, str_len - len, "4567");
62  assert_string_equal(tmp, "test string 1234567");
63 
64  test_free(str);
65 }
66 
67 static void torture_test_realloc_set0(void **state)
68 {
69  char *str;
70  size_t str_len;
71 
72  (void)state; /* unsused */
73 
74  str_len = 16;
75  str = (char *)test_malloc(str_len);
76  assert_non_null(str);
77 
78  /* realloc(ptr, 0) is like a free() */
79  str = (char *)test_realloc(str, 0);
80  assert_null(str);
81 }
82 
83 int main(void) {
84  const struct CMUnitTest alloc_tests[] = {
88  };
89 
90  return cmocka_run_group_tests(alloc_tests, NULL, NULL);
91 }
static void torture_test_realloc_set0(void **state)
Definition: test_alloc.c:67
#define assert_non_null(c)
Definition: cmocka.h:1102
#define cmocka_unit_test(f)
Initializes a CMUnitTest structure.
Definition: cmocka.h:1653
#define snprintf
Definition: config-msvc.h:96
#define test_free(ptr)
Definition: cmocka.h:1920
static void torture_test_realloc(void **state)
Definition: test_alloc.c:34
#define test_realloc(ptr, size)
Definition: cmocka.h:1907
#define assert_string_equal(a, b)
Definition: cmocka.h:1214
int main(void)
Definition: test_alloc.c:83
#define cmocka_run_group_tests(group_tests, group_setup, group_teardown)
Definition: cmocka.h:1749
#define test_malloc(size)
Definition: cmocka.h:1872
#define assert_null(c)
Definition: cmocka.h:1119
static void torture_test_malloc(void **state)
Definition: test_alloc.c:13
#define assert_int_equal(a, b)
Definition: cmocka.h:1174