Search code examples
cmpicalloc

free memory malloc MPI


What is the best way to free memory allocated before calling mpi init? In the code given below should the calloced memory deallocated before mpi finalize or after mpi finalize. Anyhow doing either way does not give any errors.

Thanks

int main (int argc, char *argv[])
{
    int   hostid, numprocessors;
    int *trial;
    trial = calloc(5,sizeof(int));
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocessors);
    MPI_Comm_rank(MPI_COMM_WORLD,&hostid);
    free(trial);
    MPI_Finalize();
    //free(trial);
    return(0);
}

Solution

  • Transferring comment into an answer to allow for closure.

    If you don't make the memory available to MPI_Init(), you can free it whenever suits you. There might be arguments of 'nesting symmetry' for doing the free after the call to MPI_Finalize(), but your code should be fine as it stands.

    Of course, the code in the question doesn't use the allocated memory anywhere. However, the observations still apply. As long as you don't free the memory before the last code using it completes, you should be fine.

    You may be able to use valgrind to validate this (…though I note the observation that valgrind does not work with MPI programs, at least on the Ubuntu environment which is, presumably, the relevant one…).