segmentation fault when resizing a vector

S

sandwich_eater

I get a segmentation fault in my program when resizing a vector. This
seems strange because it is the second resize that causes the error.

std::vector<double> a;
std::vector<double> b;

a.resize(ndata - 1);
b.resize(ndata - 1); // fault occurs here
 
M

Matthias Kaeppler

I get a segmentation fault in my program when resizing a vector. This
seems strange because it is the second resize that causes the error.

std::vector<double> a;
std::vector<double> b;

a.resize(ndata - 1);
b.resize(ndata - 1); // fault occurs here

And will you tell us what ndata is? :)
 
S

sandwich_eater

I guess it should be

a.resize(ndata);
b.resize(ndata);

but it still does not explain the error
 
M

Matthias Kaeppler

#include <vector>

int main()
{
std::vector<double> a;
std::vector<double> b;

a.resize(1);
b.resize(1);
}

This compiles and runs without segfaulting, are you /sure/ that ndata-1
evaluates to 1?

Here is what the standard requires resize() to do:

if (sz > size())
insert(end(), sz-size(), c);
else if (sz < size())
erase(begin()+sz, end());
else
; //do nothing

I'm not sure what happens if sz is negative. My compiler issues a
warning if that happens.
 
S

sandwich_eater

Changing to ndata instead of ndata - 1 solves the problem, at least the
execution point goes much further, perhaps the executable is using some
kind of look ahead and this is why the fault occurs at that point
rather than further on in my code. I am using g++ in cygwin. I think
I ndata is right rather than ndata - 1.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top