aenglert42 / dining_philosophers

A small project to learn the basics of threading a process and resource sharing. On the basis of the "dining philosophers problem", originally formulated by Edsger Dijkstra. Inspired by the "42 Coding School" exercise "philosophers" (February 2022).
2 stars 0 forks source link

Why are you doing double malloc? #1

Closed MLeganes closed 2 years ago

MLeganes commented 2 years ago

https://github.com/aenglert42/dining_philosophers/blob/41889ac7187184c660ed4ba80a5ec3465da6b0fe/src/3_allocate.c#L25

MLeganes commented 2 years ago

In line 20 you are doing malloc in Line 20 for pthread_mutex_t * Number of philos and + 1. In line 25 another malloc. Why?

aenglert42 commented 2 years ago

In line 20 I allocate for the pointers (pthread_mutex_t *) and in line 25 for the actual data (pthread_mutex_t).

MLeganes commented 2 years ago

Have you tryed to test the code without line 25? Is it working?

I think this is the same in one line: data->forks = (pthread_mutex_t )malloc(sizeof(pthread_mutex_t) (data->num_of_philos + 1));

aenglert42 commented 2 years ago

You could do this, but in my opinion it would suggest, that we are dealing with a pointer when we are actually dealing with an array of pointers. So it could be a bit misleading, I guess.