I’ve a weird problem with malloc. I have this typedefs:
typedef struct buffer {
int D;
int T;
unsigned int current_size;
unsigned int max_size;
pthread_mutex_t mutex;
pthread_cond_t non_pieno;
pthread_cond_t non_vuoto;
msg_t** messages;
struct buffer* (*buffer_init)(unsigned int);
void (*buffer_destroy)(struct buffer*);
} buffer_t;
And this is the buffer_init and buffer_destroy function:
buffer_t* buffer_init(unsigned int maxsize)
{
buffer_t* new_buffer = (buffer_t*)malloc(sizeof(buffer_t));
msg_t** new_messages = (msg_t**)calloc(maxsize, sizeof(msg_t**));
pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t np = PTHREAD_COND_INITIALIZER;
pthread_cond_t nv = PTHREAD_COND_INITIALIZER;
new_buffer->T = 0;
new_buffer->D = 0;
new_buffer->current_size = 0;
new_buffer->max_size = maxsize;
new_buffer->messages = new_messages;
new_buffer->mutex = mx;
new_buffer->non_pieno = np;
new_buffer->non_vuoto = nv;
new_buffer->buffer_init = buffer_init;
new_buffer->buffer_destroy = buffer_destroy;
return new_buffer;
}
void buffer_destroy(buffer_t* buffer) {
pthread_mutex_destroy(&buffer->mutex);
free(buffer);
}
If I print (after each call to the proper buffer_destroy buffer_init sequence) the pointers that I obtain they are most the same!!
E.g
buffer_t* my_buff;
my_buff = buffer_init(1);
printf("%d", my_buff); //e.g 10023
printf("%d", my_buff->mutex); //e.g 56778
buffer_destroy(my_buff);
my_buff = buffer_init(1);
printf("%d", my_buff); //10023 again!!!
printf("%d", my_buff->mutex); //56778 again!!!
I’m pretty sure the problems is that something goes wrong with the initialization and deallocation of the buffer_t, do you know, in order:
a) How to properly deallocate buffer into buffer_destroy?
b) How to properly init the mutex? I want to create a new mutex with each call!
c) I have to malloc for D and T? I have to dealloc them??
Thanks for your time!
A.
This doesn’t look like a problem! You’ve allocated some memory, then released it back to the system. Then you’ve asked for some more memory of the same size, and the malloc system has noticed that there’s some memory available of that size – the same memory that it gave you before!
If you remove the call to
buffer_destroy()you should see that you get different values. (By the way I recommend using “%p” for printing pointer values, rather than “%d”).