Reputation: 803
I am utterly mystified by this error, and I hope you can help me! I have a class which has a vector of structures (the structure is called particle). I am simply writing a getter which returns a vector of a certain field in the structure; once for a field called x, and then again for a field called v:
vector<double> x = s.getx();
vector<double> v = s.getv();
For some reason, getx works, but getv does not: It gives me "malloc(): memory corruption:".
Here are the classes getx and getv:
vector<double> getx() {
vector<double> ret(number-2);
for(int i = 1; i < number; i++) {
ret[i-1] = masses[i].x;
}
return ret;
}
vector<double> getv() {
vector<double> ret(number-2);
for(int i = 1; i < number; i++) {
ret[i-1] = masses[i].v;
}
return ret;
}
The error occurs on this line:
vector<double> ret(number-2);
in getv.
The reason I am so confused is that both these methods are essentially identical! I even get the same error when I replace (number-2) with a constant, e.g. 4. It simply can't allocate the memory!
I hope you can see what I've done wrong...
Thank you very much for your help, Best wishes, noctilux
Upvotes: 1
Views: 2493
Reputation: 76245
Memory corruption errors rarely show up at the point where they occur; they show up later, when something hits the corrupted memory. In this case, both functions are writing to memory that doesn't belong to them. Each one initializes a vector
with number - 2
elements, then writes to vector[number - 1]
, which doesn't exist.
Upvotes: 7