Skip to content

Commit

Permalink
Add unit-test for malloc(...) and free(...)
Browse files Browse the repository at this point in the history
  • Loading branch information
scopeInfinity committed Oct 23, 2021
1 parent e07e872 commit 99a08dd
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/usr/local/src/test-stdlib.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Expand Down Expand Up @@ -47,6 +48,53 @@ void test_ftoa() {
ASSERT_TRUE(std::strcmp(buffer, "0.15") == 0);
}

void test_malloc_free() {
// we don't want to test to be dependent on the internal
// implementation of malloc and free. So, we are ensuring
// no overlapping memory is being allocated.

const int test_order[] = {
64, // [0] allocate 64 bytes
128, // [1] allocate 128 bytes
-0, // [2] test memory and deallocate 64 bytes
1024, // [3] allocate 1024 bytes
-1, // [4] test memory and deallocate 128 bytes
100, // [5] allocate 100 bytes, it could get allocated in freed space
-5, // [6] test memory and deallocate 100 bytes
-3 // [7] test memory and deallocate 1024 bytes
};
std::uint8_t *memory_track[sizeof(test_order) / sizeof(test_order[0])];

for (std::uint8_t i = 0; i < sizeof(test_order) / sizeof(test_order[0]);
i++) {
int op = test_order[i];
if (op > 0) {
// allocate memory
memory_track[i] = (std::uint8_t *)std::malloc(op);

// put data bytes marker... in allocated memory
const std::uint8_t marker = i;
std::memset(memory_track[i], marker, test_order[i]);
} else {
int track_id = -op;

// test memory
const std::uint8_t marker = track_id;
bool is_track_memory_good = true;
for (int j = 0; j < test_order[track_id]; j++) {
if (memory_track[track_id][j] != marker) {
is_track_memory_good = false;
break;
}
}
ASSERT_TRUE(is_track_memory_good);

// free memory
std::free(memory_track[track_id]);
}
}
}

int main(int argc, char *argv[]) {
TEST_INIT();

Expand All @@ -56,6 +104,7 @@ int main(int argc, char *argv[]) {
RUN_TEST(test_atoi);
RUN_TEST(test_itoa);
RUN_TEST(test_ftoa);
RUN_TEST(test_malloc_free);

TEST_SUMMARY();
return 0;
Expand Down

0 comments on commit 99a08dd

Please sign in to comment.