Search code examples
cunit-testingfree

How to test struct deallocation


I have an opaque struct along with allocation/deallocation functions in a header file. Here is it:

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);
    }
}

The problem arose when I tried to write unit test for the release_mystruct deallocation function in order to make sure it does not cause memory leak. We cannot simply intercept all calls to free like we do in Java where I came from also redefining functions from standard library is undefined behavior.

Is there a way to approach the problem?


Solution

  • Simple answer: You can't. free doesn't give any hints if it worked as expected or not but the C standard guarantees that it will release the memory if you call it and the pointer exists. So you don't need to check for that.

    If you want to check if the free is called you can assign NULL after the free and check on that.