Mit malloc / realloc für ein Array von Klassen / Strukturen einschließlich des Standardvektors

Ich habe eine Frage zu malloc / realloc-Speicher, der ein Array von class / struct-Elementen enthält (ich habe versucht, sowohl struct als auch class zu verwenden, bei denen das Problem weiterhin besteht), die std-Vektoren enthalten. Ich weiß, dass ich das Problem umgehen kann, indem ich die Container-Klasse new und std array verwende. Ich möchte jedoch besser verstehen, warum der folgende kleine Code abstürzt, wenn ich Realloc anstelle von Malloc verwende (da ich dieses Problem beim Übergang eines größeren Code-Projekts von C auf C ++ festgestellt habe). Es scheint auch, dass ich in einer Klasse / Struktur nicht unbedingt die Anfangsgröße eines Vektors festlegen kann (manche Compiler erlauben es, manche nicht ..) - also was ist ein Vektor in einer Klasse - ein komfortabler Zeiger?

anke, K

#include <stdlib.h>
#include <limits.h>
#include <float.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <sys/types.h>
#include <vector>
/* 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<double> 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<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<10;++i){
    Comp2 =(voxel*)realloc(&Comp2[0], (i+1)*sizeof(voxel));
    Comp2[i] = v0;
  }  

  printf("realloc done\n");

  for(i=0;i<10;++i) Comp[i].y.push_back(d);
  for(i=0;i<10;++i) printf("%lf\n",Comp[i].y[0]);

  for(i=0;i<10;++i) Comp2[i].y.push_back(d); // this crashes
  for(i=0;i<10;++i) printf("%lf\n",Comp2[i].y[0]);

  return 1;
} 

Antworten auf die Frage(6)

Ihre Antwort auf die Frage