Fix leak caused by not accepting thread's return
authorLukas Jiriste <ljiriste@student.42prague.com>
Tue, 19 Mar 2024 10:23:36 +0000 (11:23 +0100)
committerLukas Jiriste <ljiriste@student.42prague.com>
Fri, 22 Mar 2024 10:01:33 +0000 (11:01 +0100)
The threads have alocatted memory where return value resides.
A thread has to be joined (or detached) to release this memory.

philo/main.c

index 31fb4324a4cab010e4862677ab208155f865e9d7..1626f837fb55105a6fffca86f3e297519ffec147 100644 (file)
@@ -6,7 +6,7 @@
 /*   By: ljiriste <marvin@42.fr>                    +#+  +:+       +#+        */
 /*                                                +#+#+#+#+#+   +#+           */
 /*   Created: 2024/03/05 12:49:40 by ljiriste          #+#    #+#             */
-/*   Updated: 2024/03/07 17:51:19 by ljiriste         ###   ########.fr       */
+/*   Updated: 2024/03/19 11:20:03 by ljiriste         ###   ########.fr       */
 /*                                                                            */
 /* ************************************************************************** */
 
@@ -249,7 +249,7 @@ int parse_input(int argc, char **argv, t_settings *set)
        int     res;
 
        if (argc != 5 && argc != 6)
-               return (0);
+               return (1);
        res = 0;
        res = res || parse_args(argv[1], &set->philo_count);
        res = res || parse_arg(argv[2], &set->time_to_die);
@@ -270,6 +270,9 @@ int init_settings(int argc, char **argv, t_settings *set)
 }
 
 
+//     "pthread_detach(threads[count]);" should be sufficient
+//     instead of pthread_join(thread[count], NULL) but valgrind
+//     then shows leaks
 void   cleanup(pthread_mutex_t *forks, t_philo *philos, pthread_t *threads, t_settings *set)
 {
        size_t  count;
@@ -279,6 +282,7 @@ void        cleanup(pthread_mutex_t *forks, t_philo *philos, pthread_t *threads, t_sett
        {
                --count;
                pthread_mutex_destroy(&forks[count]);
+               pthread_join(threads[count], NULL);
        }
        pthread_mutex_destroy(&set->terminal);
        free(forks);
@@ -335,7 +339,10 @@ int        main(int argc, char **argv)
        t_philo                 *philos;
 
        if (init_settings(argc, argv, &settings))
+       {
+               printf("Invalid input arguments.\n");
                return (1);
+       }
        threads = malloc(sizeof(pthread_t) * settings.philo_count);
        forks = init_forks(settings.philo_count);
        philos = build_philos(forks, &settings);