I am getting some very strange behavior from the vector.size() function. I created a new class and within that class created a vector object as follows.
1 2 3
class Nodes{
std::vector<int> tree;
};
I then initialize tree with a method as follows
1 2 3 4
void Nodes::buildTree(){
tree.push_back(-1);
cout << tree.size() << endl; //This line prints 1
}
The trouble comes with the following code.
1 2 3 4 5 6 7 8 9 10 11
void Nodes::buildNetwork(int depth, int node){
for (int n=0; n<nodes[node].size(); n++){
if (nodes[m][n]>=(mean[m]+stdev[m])){
cout << tree.size() << endl; //This line prints a 20 digit int
if (int i=0; i<tree.size(); i++){ //segfault occurs here due to strange behavior of tree.size();
...
}
...
}
}
}
I use the same function just above the area with the segfault with no problems. I cannot figure out why the tree.size() function returns two different values at different places in the program without the vector being changed whatsoever.
I do not write to the vector anywhere prior to that point other than when I assign the first value to -1.
I must admit I am not entirely sure how to enable debug iterators.
I don't understand how the code is not relevant to the problem I've encountered. If it isn't relevant perhaps you could be helpful and tell me why not, or tell me what would be relevant. I thought it was relevant, hence my post. So unless you can help explain why it isn't relevant and what would be relevant, your comment was not all that helpful.
Yes, there are quite a few other vectors. Most of them use a similar format to determine the size of the vector and then step through each element for comparison purposes. Not once before have I encountered this problem.
When I compile I use g++ resMap.cpp -o resMap.out
Do I turn it on from the command line or do I need to edit something else?
Either a #define _GLIBCXX_DEBUG in all translation units before including any standard headers or better, passing -D_GLIBCXX_DEBUG on the command line. In case you're on Linux or Mac, you should also run your program with valgrind (compile with debug symbols first (-g)).
I have discovered something interesting. If I move the cout line to just before the for (...){ line it prints the correct value.
1 2 3 4 5 6 7 8 9 10 11 12
void Nodes::buildNetwork(int depth, int node){
cout << tree.size() << endl; //This line prints 1
for (int n=0; n<nodes[node].size(); n++){
if (nodes[m][n]>=(mean[m]+stdev[m])){
cout << tree.size() << endl; //This line prints a 20 digit int
if (int i=0; i<tree.size(); i++){ //segfault occurs here due to strange behavior of tree.size();
...
}
...
}
}
}
As I said this code is not relevant to the problem. It is obvious that somewhere the memory is been coruppted. I think that the reason is incorrect indexes used in your array nodes.