0

Is it testable to validate if fields of mybuf_t was properly freed after free mybuf_t memory? Or I need to assume that if mybuf_destroy_fields() pass then mybuf_destroy() should be fine as its some kind of wrapper for mybuf_destroy_fields()? Its my first ever attempt to TDD things.

test_mybuf.cpp

#include "unity.h"
#include <mybuf.h>

void setUp(void){
  // set stuff up here
}

void tearDown(void){
  // clean stuff up here
}

void test_destroy_fields(){
  mybuf_t *mybuf = mybuf_init(4);
  mybuf_destroy_fields(mybuf);
  TEST_ASSERT_NULL(mybuf->data);
}

void test_destroy(){
  mybuf_t *mybuf = mybuf_init(4);
  mybuf_destroy(&mybuf);
  TEST_ASSERT_NULL(mybuf);
  ;TEST_ASSERT_NULL(mybuf->data); // <---- how to validate already non existing fields?
}

int runUnityTests(void){
  UNITY_BEGIN();
  RUN_TEST(test_destroy_fields);
  RUN_TEST(test_destroy);
  return UNITY_END();
}

int main(void){
  return runUnityTests();
}

mybuf.c (only constructor/destructor things)

void mybuf_destroy(mybuf_t **mybufp){
    mybuf_destroy_fields(*mybufp);
    if(*mybufp!=NULL){
        free(*mybufp);
        *mybufp = NULL;
    }
}

void mybuf_destroy_fields(mybuf_t *mybuf){
    if(mybuf!=NULL){
        if(mybuf->data!=NULL){
            free(mybuf->data);
            mybuf->data = NULL;
        }
    }
}

mybuf_t * mybuf_init(mybuf_size_t bufferLen){
    mybuf_t *mybuf = (mybuf_t*)calloc(sizeof(mybuf_t),1);
    
    uint32_t specialSpace = 1;
    mybuf->data = (uint8_t*)malloc(bufferLen+specialSpace);
    if(mybuf->data==NULL){
        // LOGF("błąd alokowania pamięci\n");
        return NULL;
    } else {
        mybuf->len = bufferLen;
        mybuf_set(mybuf,0,0);
    }
    return mybuf;
}
Dobijasek
  • 91
  • 1
  • 5
  • You don't have access to the "fields of `mybuf_t`" after freeing `mybuf_t` memory. – Weather Vane Jul 17 '22 at 18:19
  • 2
    You should `free()` memory in reverse order of allocation, or from the inside of a data structure outwards. If you are unsure if something was already `free`d then when you `free` it, set it to `NULL`. Then a duplicated `free()` is harmless. – Weather Vane Jul 17 '22 at 18:21
  • You'll get a nice [undefined behaviour if you attempt to access anything that was free'd.](https://stackoverflow.com/questions/15432123/using-pointer-after-free). – Zakk Jul 17 '22 at 18:23

0 Answers0