title: Best strategy in dynamic allocation in C for strcut with many pointers
body: <p>I wonder what is the best strategy for alloc memory for a struct with many pointers within.</p>
  
  <p>Like this:</p>
  
  <pre><code>struct Test{
      long unsigned int size;
      double *A;
      int *B;
      double *C;
  };
  </code></pre>
  
  <p>Then I could use many allocations, like this:</p>
  
  <pre><code>struct Test *alloc_test(long unsigned int size){
      struct Test *ans = (struct Test*)malloc(sizeof(struct Test));
      if(ans == NULL){
          return NULL;
      }
      ans-&gt;size = size;
      ans-&gt;A = (double *)malloc(sizeof(double)*size);
      if(ans-&gt;A == NULL){
          free(ans);
          return NULL;
      }
      ans-&gt;B = (int *)malloc(sizeof(int)*size);
      if(ans-&gt;B == NULL){
          free(ans-&gt;A);
          free(ans);
          return NULL;
      }
      ans-&gt;C = (double *)malloc(sizeof(double)*size);
      if(ans-&gt;C == NULL){
          free(ans-&gt;A);
          free(ans-&gt;B);
          free(ans);
          return NULL;
      }
      return ans;
  }
  </code></pre>
  
  <p>Or I could usi a single allocation, like this:</p>
  
  <pre><code>struct Test *alloc_test(long unsigned int size){
      long unsigned int mem_size = sizeof(struct Test) + sizeof(double)*2*size + sizeof(int)*size;
      struct Test *ans = (struct Test*)malloc(mem_size);
      if(ans == NULL){
          return NULL;
      }
      ans-&gt;size = size;
      ans-&gt;A = ans + sizeof(struct Test);
      ans-&gt;B = ans-&gt;A + sizeof(double)*size;
      ans-&gt;C = ans-&gt;B + sizeof(int)*size;
      return ans;
  }
  </code></pre>
  
  <p>This is possible in that sittuation because this object shouldn't be realloced. In this case, does anyone knows the advantage of each one?</p>