altroware
altroware

Reputation: 980

gdb: <error reading variable> with c++ vector

I have problem in accessing the memory for a std vector.

I first define a struct (in the header file):

typedef struct Systems {
//  other variables...
    vector <double>  sum;
} System;

I need an ensemble of system, and each vector sum must contain num doubles so, into the main, I write:

System * system;
system = (System*)malloc(DIM_ENSEMBLE*sizeof(System));
for (i =0; i< DIM_ENSEMBLE; i++) {
//...
system[i].part_sum.resize(num);
//...
}

From this point as soon as I use

System[0].part_sum[0]

to initialize the vector I receive a segmentation fault program.

If in the gdb i try to

(gdb) print system[0].part_sum[0]

I get:

$2 = (double &) @0x200000003: <error reading variable>

I obtain the same error using reserve or allocator instead of resize. I also checked the capacity of the vector

cout << system[0].part_sum.capacity();

and I sow that there is lot of space...

What is happening? Is this a problem of memory management?

A.

Upvotes: 2

Views: 8537

Answers (2)

juanchopanza
juanchopanza

Reputation: 227468

Replace your pointer tby a vector:

std::vector<System> system(DIM_ENSEMBLE);

for (i =0; i< system.size(); ++i) {
//...
system[i].part_sum.resize(num);
//...
}

You cannot initialize an array of System with malloc, because System is not a POD. Its vector data member needs to be constructed via a constructor call. The example above takes care of that.

Note that if you want to pass a pointer to the vector's underlying data to use some legacy API, you can get that via

const System* cp = system.data(); // or &system[0] if no C++11 
System* p = system.data();        // or &system[0] if no C++11

for example:

void doStuff(System*, unsigned count);

std::vector<System> test(42);
doStuff(test.data(), test.size()); // C++11
doStuff(&test[0], test.size()); // C++03

Upvotes: 6

altroware
altroware

Reputation: 980

I replaced `malloc' with 'new' and it worked.

System * system;    
system = new System[DIM_ENSEMBLE];

In this way I am still able to use the pointer system when I call the functions previously defined.

Upvotes: 1

Related Questions