释放动态分配的内存到包含指针的结构数组

Free dynamically alloted memory to struct array containing pointer

我有三个文件

struct.h  struct.c main.c

struct.h 包含结构和一些函数的声明
struct.c 包含全局变量 bglobal struct b 的实例和使用 bglobal 的函数实现。它包括 .h 文件
main.c 调用一些在 struct.h 中声明的函数。它还包括 .h 文件
struct.h 包含两个结构

struct a{
int *s
}
struct b{
struct a* arr
}
void init();
void more();

struct.c 文件

#include"struct.h"
struct b bglobal;
void init(){
   bglobal.arr = malloc(sizeof(struct a)*5);
}
void more(){
   *bglobal.arr[0].name = 'I';
}

main.c 文件

#include "main.h"
int main(){
init();
more();
}

我希望在程序结束时释放分配给 bglobal.arr 的内存。 使用 valgrind 它表示仍然可以访问一些字节。 如何实现?

I want that at end of program memory allocated to bglobal.arr get freed up.

init()

添加补函数
int main(){
  init();
  // do stuff
  uninit();  // this functions frees resources.
}

如果struct.h不允许改进,在main.c中做一个局部函数。

void uninit(void) {
  extern struct b bglobal; // Take advantage that bglobal is not static
  free(bgolbal.arr);
}

bgolbal.arr = malloc(sizeof(struct b)*5); 分配给了错误的类型。 .arr 是一个 struct a*。改为分配给引用的对象,因为它更容易正确编码、审查和维护。

bgolbal.arr = malloc(sizeof *bgolbal.arr * 5);

您需要向 struct.c 添加清理函数以释放内存。由于您无法从模块外部引用该函数,因此您可以使用 init 中的 atexit 将其设置为在程序退出时调用。

static void cleanup() {
    free(bglobal.arr);
}

void init(){
   bglobal.arr = malloc(sizeof(struct a)*5);
   atexit(cleanup);
}