I'm working on a project The project in c and The point of it is to create a multiple threads and work with them ... the problem is The program worked fine on my Macos but when I'm trying to work on the project form Kali VM or WSL (Windows Subsystem for Linux). the same code gaves me the following error
the error on kali VM
└─$ ./a.out 3 800 200 200 1200 134 ⨯
malloc(): corrupted top size
zsh: abort ./a.out 3 800 200 200 1200
The error on WSL
└─$ ./a.out 2 60 60 20
malloc(): corrupted top size
Aborted (core dumped)
you can check the full code here in this repo.
this is the main file of the code:
#include "philosophers.h"
int ft_error_put(char *messsage, int ret)
{
printf("%s\n", messsage);
return (ret);
}
int ft_parsing(char **av, t_simulation *simulation)
{
int num;
int i;
int j;
i = 1;
j = 0;
while (av[i])
{
j = 0;
num = 0;
while (av[i][j])
{
if (av[i][j] >= '0' && av[i][j] <= '9')
num = num * 10 + (av[i][j] - '0');
else
return (ft_error_put("Error: Number Only", 1));
j++;
}
if (i == 1)
{
simulation->philo_numbers = num;
simulation->forks = num;
simulation->threads = (pthread_t *)malloc(sizeof(pthread_t) * num);
}
else if (i == 2)
simulation->time_to_die = num;
else if (i == 3)
simulation->time_to_eat = num;
else if (i == 4)
simulation->time_to_sleep = num;
else if (i == 5)
simulation->eat_counter = num;
i++;
}
if (i == 5)
simulation->eat_counter = -1;
return (0);
}
void ft_for_each_philo(t_simulation *simulation, t_philo *philo, int i)
{
philo[i].index = i + 1;
philo[i].left_hand = i;
philo[i].right_hand = (i + 1) % simulation->philo_numbers;
philo[i].is_dead = NO;
if (simulation->eat_counter == -1)
philo[i].eat_counter = -1;
else
philo[i].eat_counter = simulation->eat_counter;
}
t_philo *ft_philo_init(t_simulation *simulation)
{
t_philo *philo;
int i;
i = -1;
philo = (t_philo *)malloc(sizeof(t_philo));
while (++i < simulation->philo_numbers)
ft_for_each_philo(simulation, philo, i);
return (philo);
}
void *ft_routine(void *arg)
{
t_philo *philo;
philo = (t_philo *)arg;
printf("thread number %d has started\n", philo->index);
sleep(1);
printf("thread number %d has ended\n", philo->index);
return (NULL);
}
int main(int ac, char **av)
{
int i;
t_simulation simulation;
t_philo *philo;
i = 0;
if (ac == 5 || ac == 6)
{
if (ft_parsing(av, &simulation))
return (1);
philo = ft_philo_init(&simulation);
while (i < simulation.philo_numbers)
{
simulation.philo_index = i;
pthread_create(simulation.threads + i, NULL,
ft_routine, philo + i);
i++;
}
i = 0;
while (i < simulation.philo_numbers)
{
pthread_join(simulation.threads[i], NULL);
i++;
}
}
return (0);
}