This is a code snippet of a larger program. I tried to simplify it as much as possible.
This code identifies certain particles and stores them in a list which corresponds to a certain processor.
Besides that I count the number of particles per processor that are already in the list.
After the work is done I want to use the message-passing system MPI to send the particles in the list to other processors (not shown here).
I would like to know:
- Is the process of allocation and deallocation of memory correct?
- Is the code robust?
- Can this be simplified?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DIM 2
typedef struct{
double m;
double x[DIM];
double v[DIM];
int id;
} Particle;
typedef struct{
double **list;
int *counter;
} ParticleList;
void generateParticles(Particle *p, int N);
void buildList(Particle *p, ParticleList *plist, int numprocs, int N);
int main() {
time_t t;
srand((unsigned)time(&t));
// Generate data, print data
int N = 50;
Particle *p = (Particle*)malloc(N*sizeof(*p));
generateParticles(p, N);
for(int i=0; i<N; i++){
printf("id: %d m: %lf x: %lf %lf v: %lf %lf\n", p[i].id, p[i].m, p[i].x[0], p[i].x[1], p[i].v[0], p[i].v[1]);
}
// Fill lists of every processor
int numprocs = 4;
ParticleList plist;
plist.list = malloc(sizeof(double*)*numprocs);
for(int k=0; k<numprocs; k++)
plist.list[k] = malloc(sizeof(double)*1);
plist.counter = calloc(numprocs, sizeof(int));
buildList(p, &plist, numprocs, N);
for(int k=0; k<numprocs; k++){
printf("Processor %d Particles in list %d\n", k, plist.counter[k]);
for(int c=0; c<(DIM*plist.counter[k]); c++){
printf("%lf ", plist.list[k][c]);
}
printf("\n");
}
// deallocate memory
for(int k=0; k<numprocs; k++){
free(plist.list[k]);
}
free(plist.list);
free(plist.counter);
free(p);
return 0;
}
void buildList(Particle *p, ParticleList *plist, int numprocs, int N){
for(int k=0; k<numprocs; k++){
for(int i=0; i<N; i++){
printf("k %d, i %d\n", k, i);
if(rand()%10 < 5){
plist->counter[k] = plist->counter[k] + 1;
plist->list[k] = realloc(plist->list[k], (DIM*plist->counter[k])*sizeof(plist->list[k][0]));
int d=0;
for(int j=(plist->counter[k] - 1)*DIM; j < (plist->counter[k] * DIM); j++){
plist->list[k][j] = p[i].x[d];
d++;
}
}
}
}
}
double frand(){
return (double)rand() / (double)RAND_MAX;
}
void generateParticles(Particle *p, int N){
for(int i=0; i<N; i++){
for(int d=0; d<DIM; d++){
p[i].x[d] = frand();
p[i].v[d] = frand();
}
p[i].m = frand();
p[i].id = i;
}
}