c - 如何测试结构释放

标签 c unit-testing free

我在头文件中有一个不透明的结构以及分配/释放函数。这是它:

my_strct.h:

typedef struct helper helper;
helper *allocate_helper(void);
void release_helper(helper *helper_ptr);

typedef struct my_struct;
my_struct *allocate_mystruct(void);
void release_mystruct(my_struct *ptr);

my_strct.c:

#include "my_strct.h"

struct helper{
    const char *helper_info;
}

helper *allocate_helper(void){
     return malloc(sizeof(struct helper));
}

void release_helper(helper *helper_ptr){
     if(helper_ptr){
         free(helper_ptr -> helper_info);
         free(helper_ptr);
     }
}

struct my_struct{
     const char *info;
     const char *name;
     struct helper *helper_ptr
}

my_struct *allocate_mystruct(void){
    struct my_struct *mystruct_ptr = malloc(sizeof(mystruct_ptr));
    mystruct_ptr -> helper_ptr = allocate_helper(); 
}

void release_mystruct(struct my_struct *mystruct_ptr){
    if(mystruct_ptr){
        release_helper(mystruct_ptr -> helper_ptr);
        free(mystruct_ptr -> info);
        free(mystruct_ptr -> name);
        free(mystruct_ptr);
    }
}

当我尝试为 release_mystruct 释放函数编写单元测试以确保它不会导致内存泄漏时,出现了问题。我们不能简单地拦截所有对 free 的调用,就像我在 Java 中所做的那样,从标准库中重新定义函数也是未定义的行为。

有没有办法解决这个问题?

最佳答案

简单的回答:你不能。 free 不会给出任何提示是否按预期工作,但 C 标准保证,如果您调用它并且指针存在,它将释放内存。所以你不需要检查这一点。

如果你想检查 free 是否被调用,你可以在 free 之后分配 NULL 并检查。

关于c - 如何测试结构释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55470073/

相关文章:

c - 在 c 中的结构成员中间调用 free 时会发生什么?

C - free() 没有释放整个数组

这可以被认为是可接受的 goto 使用吗?

c - 具有灵活阵列成员的不透明结构

c - do while 循环中未声明的标识符,C

.NET 测试命名约定

c - 用于 IPC 的 sprintf 或 itoa 或 memcpy

node.js - 带有 proxyquire 和 sinon 的 google-geocoder

unit-testing - 有副作用的单元测试方法

c - 一次释放堆上多个区域的机制