如何测试结构释放

How to test struct deallocation

我在头文件中有一个不透明结构以及 allocation/deallocation 函数。在这里:

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 是否按预期工作,则 free 不会给出任何提示,但 C 标准保证如果您调用它并且指针存在,它将释放内存。所以你不需要检查那个。

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