title: Is there a better/cleaner/more elegant way to malloc and free in cuda?
body: <p>I am trying to cudaMalloc a bunch of device pointers, and gracefully exit if any of the mallocs didn't work.  I have functioning code - but bloated because I have to cudaFree everything I'd previously malloc'd if one fails.  So now I am wondering if there is a more succinct method of accomplishing this.  Obviously I can't free something that hasn't been malloc'd - that will definitely cause problems.</p>
  
  <p>Below is the snippet of code I am trying to make more elegant.</p>
  
  <pre><code>    //define device pointers
      float d_norm, *d_dut, *d_stdt, *d_gamma, *d_zeta;
  
      //allocate space on the device for the vectors and answer
      if (cudaMalloc(&amp;d_norm, sizeof(float)*vSize) != cudaSuccess) {
              std::cout &lt;&lt; "failed malloc";
              return;
      };
  
      if (cudaMalloc(&amp;d_data, sizeof(float)*vSize) != cudaSuccess) {
              std::cout &lt;&lt; "failed malloc";
              cudaFree(d_norm);
              return;
      };
  
      if (cudaMalloc(&amp;d_stdt, sizeof(float)*wSize) != cudaSuccess) {
              std::cout &lt;&lt; "failed malloc";
              cudaFree(d_norm);
              cudaFree(d_data);
              return;
      };
  
      if (cudaMalloc(&amp;d_gamma, sizeof(float)*vSize) != cudaSuccess) {
              std::cout &lt;&lt; "failed malloc";
              cudaFree(d_norm);
              cudaFree(d_dut);
              cudaFree(d_stdt);
              return;
      };
  
      if (cudaMalloc(&amp;d_zeta, sizeof(float)*w) != cudaSuccess) {
              std::cout &lt;&lt; "failed malloc";
              cudaFree(d_norm);
              cudaFree(d_dut);
              cudaFree(d_stdt);
              cudaFree(d_gamma);
              return;
      };
  </code></pre>
  
  <p>This is a shortened version, but you can see how it just keeps building.  In reality I am trying to malloc about 15 arrays.  It starts getting ugly - but it works correctly.</p>
  
  <p>Thoughts?  </p>