typedef struct
{
/** animal can be DEAD or ALIVE*/
AnimalStatus status;
/** animal type, bear, bird, panda*/
AnimalType type;
/** its location in 2D site grid*/
Location location;
} Animal;
/example usage/
Animal bird, bear, panda;
/** type of Hunter*/
typedef struct
{
/** points indicate the number of animals, a hunter killed*/
int points;
/** its location in the site grid*/
Location location;
} Hunter;
/** type of a site (a cell in the grid)/
typedef struct
{
/** array of pointers to the hunters located at this site/
Hunter hunters;
/ the number of hunters at this site*/
int nhunters;
/** array of pointers to the animals located at this site*/
Animal animals;
/ the number of animals at this site*/
int nanimals;
/** the type of site*/
SiteType type;
} Site;
/** 2D site grid*/
typedef struct
{
/** number of rows, length at the x-coordinate*/
int xlength;
/** number of columns, length at the y-coordinate*/
int ylength;
/** the 2d site array*/
Site **sites;
} Grid;
@brief prints the number animals and hunters in each site
of a given grid
@param grid
*/
void
printgrid ()
{
for (int i = 0; i < grid.xlength; i++)
{
for (int j = 0; j < grid.ylength; j++)
{
Site site = &grid.sites[i][j];
int count[3] = { 0 }; / do not forget to initialize */
for (int a = 0; a < site->nanimals; a++)
{
Animal *animal = site->animals[a];
count[animal->type]++;
}
if (animal->location.x < 0)
animal->location.x = 0;
if (animal->location.y < 0)
animal->location.y = 0;
if (animal->location.x >= grid.xlength)
animal->location.x = grid.xlength - 1;
if (animal->location.y >= grid.ylength)
animal->location.y = grid.ylength - 1;
return;
}
/**
@brief it moves a given hunter or animal
randomly in the grid
@param args is an animalarray
@return void*
*/
void *
simulateanimal (void *args)
{
/*TODO: complete this function:
get animal type,
check if animal dies,
then chose random direction and move
make sure to update site.animals
then sleep
*/
while (c == 1)
{
// Check if the animal is dead
if (animal->status == DEAD)
{
// Free resources and terminate the thread
pthread_exit (NULL);
}
code
Site *site = &grid.sites[animal->location.x][animal->location.y];
// Animal behavior based on the site type
if (site->type == NESTING)
{
// Populate 1 of its kind at that site and move to a neighboring random location
// Create a new animal of the same type
Animal *new_animal = (Animal *) malloc (sizeof (Animal));
// Animal *new_animal = createanimal(animal->type, animal->location.x, animal->location.y);
*new_animal = *animal;
new_animal->location = animal->location;
site->animals[site->nanimals++] = new_animal; //CREATE ANIMAL DIYE FONK MU VAR AMK
pthread_t animal_threads[num_animals];
pthread_create (&animal_threads[num_animals], NULL, simulateanimal,
(void *) new_animal);
num_animals++;
// }
// Move to a neighboring random location
move (animal, site);
}
else if (site->type == WINTERING)
{
// Die with 0.5 probability or live and move to a neighboring random location
if (rand () % 2 == 0)
{
// Die
animal->status = DEAD;
}
else
{
// Move to a neighboring random location
move (animal, site);
}
}
else if (site->type == FEEDING)
{
// Stay with 0.8 probability or move to a neighboring random location
if (rand () % 10 < 2)
{
// Move to a neighboring random location
move (animal, site); //BU NEYI RETURN EDER
}
}
// Sleep for 1 millisecond
usleep (1000);
}
return NULL;
}
/**
@brief simulates the moving of a hunter
@param args
@return void*
*/
void *
simulatehunter (void *args)
{
/*TODO: get random position and move,
then kill all the animals in this site,
increase count,
then sleep */
while (c == 1)
{
// Get a random position and move
code
int newX = rand () % 3 - 1; //-1 0 1
int newY = rand () % 3 - 1;
// Update the hunter's location
hunter->location.x += newX;
hunter->location.y += newY;
if (hunter->location.x < 0)
hunter->location.x = 0;
if (hunter->location.y < 0)
hunter->location.y = 0;
if (hunter->location.x >= grid.xlength)
hunter->location.x = grid.xlength - 1;
if (hunter->location.y >= grid.ylength)
hunter->location.y = grid.ylength - 1;
// Kill all the animals in the site and increase the count
Site *site = &grid.sites[hunter->location.x][hunter->location.y];
for (int i = 0; i < site->nanimals; i++)
{
site->animals[i]->status = DEAD;
hunter->points++;
}
// Sleep for 1 millisecond
usleep (1000);
}
return NULL;
}
/**
the main function for the simulation
*/
int main (int argc, char *argv[])
{
/TODO argv[1] is the number of hunters /
/ if (argc != 2)
{
printf ("Hata:Mesela ./main 2 Eeklinde yazmanD1z gerekir. \n");
return 1;
}
int num_hunters =atoi (argv[1]); //BU KISIM YERINE 4 VS GIREREK DENENEBILIR SORUNSA/
int num_hunters= 7;
time_t start_time = time (NULL);
initgrid (5, 5);
/*TODO: init threads for each animal, and hunters,
the program should end after 1 second
*/
srand(time(0));
// location.x = rand () % grid.xlength;
// location.y = rand () % grid.ylength;
pthread_t animal_threads[num_animals];
for (int i = 0; i < num_animals; i++)
{
pthread_create (&animal_threads[i], NULL, simulateanimal,
(void *) &animals[i]);
}
pthread_t hunter_threads[num_hunters];
for (int i = 0; i < num_hunters; i++)
{
pthread_create (&hunter_threads[i], NULL, simulatehunter,
(void *) &hunters[i]);
}
while (1)
{
time_t current_time = time (NULL); // Get the current time
if ((current_time - start_time) > 1)
{
c = 0;
break; // Elapsed time exceeded 1 second, break the loop
}
}
for (int i = 0; i < num_animals; i++)
{
pthread_join (animal_threads[i], NULL);
}
for (int i = 0; i < num_hunters; i++)
{
pthread_join (hunter_threads[i], NULL);
}
printgrid ();
deletegrid ();
return 0;
}
This is the code. Why it doesnt print the grid?
Assistant
There are two primary issues in the code:
The initialization of the animal array is incorrect.
The memory allocation for the new animal during the NESTING case is not done correctly.
Let's address these issues:
The initialization of the animal array should be done properly. You can create a function like this:
With these changes, the code should work as expected and print the grid at the end of the simulation.
User
do this without creating a function and mallocs
Assistant
If you wish to avoid using a separate function and mallocs, you can initialize the animal array and create new animals directly in the main function and the simulateanimal function. Here's how to do it:
Initialize the animals array directly in the main function:
c
Animal animals[num_animals];
for (int i = 0; i < num_animals; i++) {
AnimalType animal_type = (AnimalType)(i % 3);
int x = rand() % grid.xlength;
int y = rand() % grid.ylength;
animals[i].status = ALIVE;
animals[i].type = animal_type;
animals[i].location.x = x;
animals[i].location.y = y;
}
Create new animals directly in the NESTING case in the simulateanimal function:
Note that when you do this, you'll also need to update the parameter type of the simulateanimal function to Animal instead of Animal *. And you should also update the function to work with the new parameter type.
However, this method is not recommended because it may lead to undefined behavior since the new_animal variable's scope is local to the simulateanimal function, and it gets destroyed when the function exits. To avoid such issues, it's best to allocate memory on the heap using malloc as shown in the previous solution.
User
look ı havent changed anything. I just moved initializations to the main function and it gives a blank output
Assistant
Apologies for the confusion. I now see you were referring to the given code with only the initialization removed. I took a closer look at your original code, and there is an issue with how the animal array is initialized. The code is creating an array of Animal pointers but initializes their values. Here is my suggestion to fix the initialization issues in the given code:
Remove the malloc statements for animals since they are handled directly in the main function.
Change the animal pointer array creation in main function from:
c
Animal *animals[num_animals];
to
c
Animal animals[num_animals];
Update the for loop of the main function:
c
for (int i = 0; i < num_animals; i++) {
animals[i].status = ALIVE;
animals[i].type = (AnimalType)(i % 3);
animals[i].location.x = rand() % grid.xlength;
animals[i].location.y = rand() % grid.ylength;
}
Call pthread_create with the address of the elements of the animals array:
However, keep in mind that moving the initialization of animals to main does not solve the other issues I described before. I recommend creating a separate function, createanimal() and using malloc as it can help prevent undefined behavior during the simulation.
If you still see a blank output, the code might be working correctly, but the output result may not show any changes due to the randomly generated movements of animals and hunters. Since the simulation only runs for 1 second, try increasing the duration and verify if the output changes over time.
User
2nd point doesnt change anything.
Assistant
I apologize for the misunderstanding. Your initial code does initialize the animal array but does not place the animals on the grid sites. To correct the code, and place the animals onto the grid, add these lines to the for loop that initializes animals in the main function:
Now the program should print the grid with initialized animals. However, it still does not guarantee that the output will show significant changes since the simulation only runs for 1 second. Changing the simulation duration or adjusting animal and hunter behaviors may provide more noticeable results.
typedef struct
{
/** animal can be DEAD or ALIVE*/
AnimalStatus status;
/** animal type, bear, bird, panda*/
AnimalType type;
/** its location in 2D site grid*/
Location location;
} Animal;
/example usage/
Animal bird, bear, panda;
/** type of Hunter*/
typedef struct
{
/** points indicate the number of animals, a hunter killed*/
int points;
/** its location in the site grid*/
Location location;
} Hunter;
/** type of a site (a cell in the grid)/
typedef struct
{
/** array of pointers to the hunters located at this site/
Hunter hunters;
/ the number of hunters at this site*/
int nhunters;
/** array of pointers to the animals located at this site*/
Animal animals;
/ the number of animals at this site*/
int nanimals;
/** the type of site*/
SiteType type;
} Site;
/** 2D site grid*/
typedef struct
{
/** number of rows, length at the x-coordinate*/
int xlength;
/** number of columns, length at the y-coordinate*/
int ylength;
/** the 2d site array*/
Site **sites;
} Grid;
@brief prints the number animals and hunters in each site
of a given grid
@param grid
*/
void
printgrid ()
{
for (int i = 0; i < grid.xlength; i++)
{
for (int j = 0; j < grid.ylength; j++)
{
Site do not forget to initialize */
for (int a = 0; a < site->nanimals; a++)
{
Animal *animal = site->animals[a];
count[animal->type]++;
}
Assistant
I apologize for the oversight on the previous response. Please replace the code block I provided earlier with the correct code snippet below:
Now, your code should initialize the animals and place them onto the grid. After this change, you should see the grid including the initial placement of animals. As mentioned before, the changes during the 1-second simulation might not be significant enough to clearly observe in the output. You could try increasing the simulation duration if you want to see more changes in the grid.
User
It says realloc(): invalid next size
Assistant
I apologize for the confusion. The issue is caused by reallocation within a loop without checking for a NULL pointer. To fix this issue, you need to update the realloc() line in the for loop like this:
Now your code should work correctly, and you should be able to see the grid with the initial positions of the animals.
User
It says double free or corruption (out)double free or corruption (!prev)
Assistant
I apologize for the oversight in my previous response. Based on the error message, it appears that there is a double-free or memory corruption issue. Most likely, the issue arises due to improper handling of the site->animals pointer.
To fix this, substitute the realloc() function with a manual memory allocation and assignment for site->animals:
The changes above should resolve the double-free or corruption error. Please give it a try and let me know if it works for you.
User
It says realloc(): invalid pointer
Assistant
My apologies for the inconvenience. It appears that we need to handle the initial memory allocation case for site->animals. Let's update the for loop once again, and allocate memory only when site->nanimals was previously 0:
c
Animal animals[num_animals];
for (int i = 0; i < num_animals; i++) {
animals[i].status = ALIVE;
animals[i].type = (AnimalType)(i % 3);
animals[i].location.x = rand() % grid.xlength;
animals[i].location.y = rand() % grid.ylength;
Site *site = &grid.sites[animals[i].location.x][animals[i].location.y];
site->nanimals++;
// Allocate memory for site->animals when site->nanimals was 0
if (site->nanimals == 1) {
site->animals = (Animal **)malloc(sizeof(Animal *));
} else {
site->animals = (Animal **)realloc(site->animals, sizeof(Animal *) * site->nanimals);
}
site->animals[site->nanimals - 1] = &animals[i];
}
Now, the code should handle the initial allocation and reallocation of the site->animals pointer appropriately.
@return void*
*/
void *
simulateanimal (void *args)
{
/*TODO: complete this function:
get animal type,
check if animal dies,
then chose random direction and move
make sure to update site.animals
then sleep
*/
@return void*
*/
void *
simulatehunter (void *args)
{
/*TODO: get random position and move,
then kill all the animals in this site,
increase count,
then sleep */
int newX, newY;
do{
newX = rand () % 3 - 1;
newY = rand () % 3 - 1;
}while(newX==0 && newY == 0);
hunter->location.x += newX;
hunter->location.y += newY;
if (hunter->location.x < 0)
hunter->location.x = 0;
if (hunter->location.y < 0)
hunter->location.y = 0;
if (hunter->location.x >= grid.xlength)
hunter->location.x = grid.xlength - 1;
if (hunter->location.y >= grid.ylength)
hunter->location.y = grid.ylength - 1;
// Kill all the animals in the site and increase the count
Site *site = &grid.sites[hunter->location.x][hunter->location.y];
for (int i = 0; i < site->nanimals; i++)
{
site->animals[i]->status = DEAD;
hunter->points++;
}
usleep (1000);
}
return NULL;
}
/**
the main function for the simulation
*/
int main (int argc, char *argv[] )
{
/TODO argv[1] is the number of hunters /
/ if (argc != 2)
{
printf ("Hata:Mesela ./main 2 Eeklinde yazmanD1z gerekir. \n");
return 1;
}
int num_hunters =atoi (argv[1]); //BU KISIM YERINE 4 VS GIREREK DENENEBILIR SORUNSA/
int num_hunters= 7;
time_t start_time = time (NULL);
initgrid (5, 5);
/*TODO: init threads for each animal, and hunters,
the program should end after 1 second
*/
srand(time(0));