#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; pthread_mutex_init(&sm_ptr->mutex, NULL); } /* create a new active pointer */ void* new_pointer(struct smart_pointer *sm_ptr) { pthread_mutex_lock(&sm_ptr->mutex); 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); } } void* res = sm_ptr->ptr; pthread_mutex_unlock(&sm_ptr->mutex); return res; } /* 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) { pthread_mutex_lock(&sm_ptr->mutex); sm_ptr->nb_ptr--; if(sm_ptr->nb_ptr == 0) { free(sm_ptr->ptr); sm_ptr->ptr = NULL; } pthread_mutex_unlock(&sm_ptr->mutex); }