title: Using malloc/realloc for array of classes/structs including std vector
body: <p>I have a question wrt malloc/realloc memory that will contain an array of class/struct (i tried both struct and class the issue remains) members that include std vectors. I know I can circumvent the problem by using new and std array container class. However, I'd like to better understand why the following little code crashes when I use realloc instead of malloc (as I encountered this problem in the context of transitioning a larger code project from C to C++). It also seems that I cannot necessarily set an initial size of a vector in a class/struct (some compilers allow some don't ..)- so what is a vector in a class - a comfortable pointer? </p>
  
  <p>Thanks,
  Kai</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;limits.h&gt;
  #include &lt;float.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;math.h&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;vector&gt;
  /* mpic++ -O3 -ffast-math -pedantic vec-alloc.cpp -o vec-alloc */
  
  using namespace std;
  
  class float_vector{
  public:
    double x;
    double y;
    double z;
    float_vector() : x(0), y(0), z(0) {};
  };
  
  
  class voxel{
  public:
    float_vector   x;
    vector&lt;double&gt; y;
  
    voxel() : x() {};
  };
  
  int main(){
  
    int i;
    double d =1.111;
    voxel v0, *Comp, *Comp2;
  
    /* dynamically allocate memory */
    Comp= (voxel*)malloc(10*sizeof(voxel));
    for(i=0;i&lt;10;++i) Comp[i] = v0;
    printf("malloc done\n");
  
    /* dynamically re-allocate memory */
    Comp2= (voxel*)malloc(sizeof(voxel));  
    printf("realloc done\n");
    for(i=0;i&lt;10;++i){
      Comp2 =(voxel*)realloc(&amp;Comp2[0], (i+1)*sizeof(voxel));
      Comp2[i] = v0;
    }  
  
    printf("realloc done\n");
  
    for(i=0;i&lt;10;++i) Comp[i].y.push_back(d);
    for(i=0;i&lt;10;++i) printf("%lf\n",Comp[i].y[0]);
  
    for(i=0;i&lt;10;++i) Comp2[i].y.push_back(d); // this crashes
    for(i=0;i&lt;10;++i) printf("%lf\n",Comp2[i].y[0]);
  
    return 1;
  } 
  </code></pre>