Segmentation fault In the Cascaded Struct Pointers Test Code
The following dummy test code gives segmentation fault at the end of execut开发者_JAVA技巧ion (to be more specific in main at return 0). I wondered the reason of this behavior. Would it be because it couldn't free the dummy variable? I'm using g++ 4.4 with no optimization flags for the tests.
#include <vector>
#include <boost/multi_array.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using std::vector;
typedef boost::multi_array<float, 1> DVec;
class Point{
public:
int x, y;
double *dist;
DVec dir;
};
struct another_struct {
vector <Point *>c;
};
struct in_foo{
vector <another_struct *>aVec;
char *aname;
float b;
};
struct foo {
DVec b;
vector<in_foo *> mVec;
};
int main(){
DVec c(boost::extents[4]);
foo **dummy = (foo **) calloc(4, sizeof(*dummy));
vector <in_foo *>test_var(5);
for(int i =0; i < 6; i++){
test_var[i] = (in_foo *) malloc(sizeof(in_foo));
memset(test_var[i], 0, sizeof(*test_var[i]));
test_var[i]->aname = "42!\n";
test_var[i]->b = (float) i;
}
for (int i = 0 ; i < 4; i++) {
dummy[i] = (foo *) malloc(sizeof(*dummy[i]));
(dummy[i]->b).resize(boost::extents[2]);
(dummy[i]->mVec) = test_var;
}
for (int i = 0 ; i < 4; i++) {
for(int j = 0; j < 5; j++){
(dummy[i]->mVec[j]->aVec).resize(5);
for (int n = 0; n < 6; n++) {
dummy[i]->mVec[j]->aVec[n] = new another_struct();
(dummy[i]->mVec[j]->aVec[n])->c.resize(3);
for (int m = 0; m < 4; m++) {
(dummy[i]->mVec[j]->aVec[n]->c[m]) = new Point();
(dummy[i]->mVec[j]->aVec[n]->c[m])->x = 100 * n;
(dummy[i]->mVec[j]->aVec[n]->c[m])->y = 11000 * m;
(dummy[i]->mVec[j]->aVec[n]->c[m])->dist = new double[2];
(dummy[i]->mVec[j]->aVec[n]->c[m])->dist[0] = 11200.123;
(dummy[i]->mVec[j]->aVec[n]->c[m])->dist[1] = 66503.131;
printf("x: %d, y: %d, dist 0: %f, dist 1: %f \n", (dummy[i]->mVec[j]->aVec[n]->c[m])->x, (dummy[i]->mVec[j]->aVec[n]->c[m])->y, (dummy[i]->mVec[j]->aVec[n]->c[m])->dist[0], (dummy[i]->mVec[j]->aVec[n]->c[m])->dist[1]);
}
}
printf("b: %f aname: %s \n", dummy[i]->mVec[j]->b, dummy[i]->mVec[j]->aname);
}
}
if (NULL != dummy) {
for(int i = 0; i < 4; i++)
{
free(dummy[i]);
}
free(dummy);
}
return 0;
}
You can't use malloc
or calloc
to allocate memory for a class or struct that is non-POD, for example vector
, foo
, in_foo
. Once you do that all bets are off and any behavior your program displays is within reason.
Use new
with smart pointers or better yet use composition if possible.pointers with new
.
精彩评论