我在头文件中有一个不透明的结构和分配/取消分配函数。给你:
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
我还从标准库中重新定义了函数,这是未定义的行为。
有办法解决这个问题吗?