Skip to content

Commit 99a08dd

Browse files
committed
Add unit-test for malloc(...) and free(...)
1 parent e07e872 commit 99a08dd

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/usr/local/src/test-stdlib.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#include <stddef.h>
12
#include <stdio.h>
23
#include <stdlib.h>
34
#include <string.h>
@@ -47,6 +48,53 @@ void test_ftoa() {
4748
ASSERT_TRUE(std::strcmp(buffer, "0.15") == 0);
4849
}
4950

51+
void test_malloc_free() {
52+
// we don't want to test to be dependent on the internal
53+
// implementation of malloc and free. So, we are ensuring
54+
// no overlapping memory is being allocated.
55+
56+
const int test_order[] = {
57+
64, // [0] allocate 64 bytes
58+
128, // [1] allocate 128 bytes
59+
-0, // [2] test memory and deallocate 64 bytes
60+
1024, // [3] allocate 1024 bytes
61+
-1, // [4] test memory and deallocate 128 bytes
62+
100, // [5] allocate 100 bytes, it could get allocated in freed space
63+
-5, // [6] test memory and deallocate 100 bytes
64+
-3 // [7] test memory and deallocate 1024 bytes
65+
};
66+
std::uint8_t *memory_track[sizeof(test_order) / sizeof(test_order[0])];
67+
68+
for (std::uint8_t i = 0; i < sizeof(test_order) / sizeof(test_order[0]);
69+
i++) {
70+
int op = test_order[i];
71+
if (op > 0) {
72+
// allocate memory
73+
memory_track[i] = (std::uint8_t *)std::malloc(op);
74+
75+
// put data bytes marker... in allocated memory
76+
const std::uint8_t marker = i;
77+
std::memset(memory_track[i], marker, test_order[i]);
78+
} else {
79+
int track_id = -op;
80+
81+
// test memory
82+
const std::uint8_t marker = track_id;
83+
bool is_track_memory_good = true;
84+
for (int j = 0; j < test_order[track_id]; j++) {
85+
if (memory_track[track_id][j] != marker) {
86+
is_track_memory_good = false;
87+
break;
88+
}
89+
}
90+
ASSERT_TRUE(is_track_memory_good);
91+
92+
// free memory
93+
std::free(memory_track[track_id]);
94+
}
95+
}
96+
}
97+
5098
int main(int argc, char *argv[]) {
5199
TEST_INIT();
52100

@@ -56,6 +104,7 @@ int main(int argc, char *argv[]) {
56104
RUN_TEST(test_atoi);
57105
RUN_TEST(test_itoa);
58106
RUN_TEST(test_ftoa);
107+
RUN_TEST(test_malloc_free);
59108

60109
TEST_SUMMARY();
61110
return 0;

0 commit comments

Comments
 (0)