1 #include <errno.h> 2 #include <gtest/gtest.h> 3 #include <malloc.h> 4 #include <stdint.h> 5 6 using namespace testing::ext; 7 8 class MallocCallocTest : public testing::Test { SetUp()9 void SetUp() override {} TearDown()10 void TearDown() override {} 11 }; 12 13 constexpr size_t LEN = 200; 14 constexpr size_t SIZE = 100; 15 16 /** 17 * @tc.name: calloc_001 18 * @tc.desc: The testing viewpoint is to verify whether the calloc function can correctly handle errors and return 19 * nullptr when passing illegal parameters, and whether errno is set to the appropriate error code. 20 * @tc.type: FUNC 21 */ 22 HWTEST_F(MallocCallocTest, calloc_001, TestSize.Level1) 23 { 24 void* memoryBlock = calloc(-1, LEN); 25 EXPECT_EQ(memoryBlock, nullptr); 26 EXPECT_EQ(errno, ENOMEM); 27 } 28 29 /** 30 * @tc.name: calloc_002 31 * @tc.desc: This test verifies that the calloc function can successfully allocate a memory block of the specified size, 32 * and the allocated memory block size meets the expected value. 33 * @tc.type: FUNC 34 */ 35 HWTEST_F(MallocCallocTest, calloc_002, TestSize.Level1) 36 { 37 void* block = calloc(1, SIZE); 38 ASSERT_NE(block, nullptr); 39 EXPECT_LE(SIZE, malloc_usable_size(block)); 40 free(block); 41 } 42 43 /** 44 * @tc.name: calloc_003 45 * @tc.desc: This test verifies that when calling the calloc function, passing 0 as the number and size of elements, the 46 * function can successfully allocate memory and return a non null pointer. 47 * @tc.type: FUNC 48 */ 49 HWTEST_F(MallocCallocTest, calloc_003, TestSize.Level1) 50 { 51 void* memoryBlock = calloc(0, 0); 52 ASSERT_NE(memoryBlock, nullptr); 53 free(memoryBlock); 54 } 55 56 /** 57 * @tc.name: calloc_004 58 * @tc.desc: This test verifies that when calling the calloc function, passing 0 as the number of elements and non-zero 59 * size, the function can successfully allocate memory and return a non-null pointer. 60 * @tc.type: FUNC 61 */ 62 HWTEST_F(MallocCallocTest, calloc_004, TestSize.Level1) 63 { 64 void* memoryBlock = calloc(0, 1); 65 ASSERT_NE(memoryBlock, nullptr); 66 free(memoryBlock); 67 } 68 69 /** 70 * @tc.name: calloc_005 71 * @tc.desc: This test verifies that when calling the calloc function, the function can successfully allocate memory and 72 * return a non null pointer when passing in a non-zero number of elements and a zero size. 73 * @tc.type: FUNC 74 */ 75 HWTEST_F(MallocCallocTest, calloc_005, TestSize.Level1) 76 { 77 void* memoryBlock = calloc(1, 0); 78 ASSERT_NE(memoryBlock, nullptr); 79 free(memoryBlock); 80 }