#include #include #include "smart_pointers.h" /* Initialize a smart pointer */ void init_smart_malloc(struct smart_pointer *sm_ptr, size_t buffer_size) { sm_ptr->nb_ptr = 0; sm_ptr->buffer_size = buffer_size; } /* create a new active pointer */ void* new_pointer(struct smart_pointer *sm_ptr) { sm_ptr->nb_ptr++; if(sm_ptr->nb_ptr == 1) { /* allocate the buffer */ sm_ptr->ptr = malloc(sm_ptr->buffer_size); if(sm_ptr->ptr == NULL) { fprintf(stderr, "Failed to allocate %lu bytes\n", sm_ptr->buffer_size); } } return sm_ptr->ptr; } /* decrement the number of active pointers, and free the buffer if there are no * more active pointers */ void smart_pointer_free(struct smart_pointer *sm_ptr) { sm_ptr->nb_ptr--; if(sm_ptr->nb_ptr == 0) { free(sm_ptr->ptr); sm_ptr->ptr = NULL; } }