title: How to determine if an MPI communicator is valid?
body: <p>In my program, I have wrapped up some MPI communicators in to a data structure. Unfortunately, sometimes the destructor of an object of this type might get called before it has been initialized. In my destructor, I of course call <code>MPI_Comm_Free</code>. But if this is called on an invalid communicator the code crashes.</p>
  
  <p>I've been looking through the MPI standard, but I can't find a function to test if a communicator is valid. I also assume I can't use <code>MPI_Comm_set_errhandler</code> to try and catch the free exception because there isn't a valid communicator to set the handler of. I could maintain a flag value of my own saying if the communicator is valid, but I prefer to avoid duplicating state information like that. Is there any built in way I can safely check if a communicator is valid?</p>
  
  <p>Here is a basic program demonstrating my problem:</p>
  
  <pre><code>#include &lt;mpi.h&gt;
  typedef struct {
    MPI_Comm comm;
  } mystruct;
  
  
  void cleanup(mystruct* a) {
    MPI_Comm_free(&amp;(a-&gt;comm));
  }
  
  int main(int argc, char* argv[]) {
    MPI_Init(&amp;argc, &amp;argv);
    mystruct a;
  
    /* Some early exit condition triggers cleanup without
       initialization */
    cleanup(&amp;a);
    MPI_Finalize();
    return 0;
  }
  </code></pre>