mercredi 4 mars 2015

Segmentation Error C++


I am fairly new to the C++ language and I am trying to write a recursive method to traverse a tree. I have a traverse method but there is one line of code that causes a segmentation fault. I have tested this by commenting and uncommenting the line, compiling and executing. I have researched why segmentation errors are caused and do not see why any of what I am doing is causing a problem with the memory. Can someone give me advice about what I am doing wrong?



int Traversal::traverse()
{
#ifdef EBUG
Utils::logStream << TAG << "enter traverse\n";
#endif
headNode = theNodes[0];
std::vector<int> downLinks = headNode.getDownLinks();
for(int i = 0; i < downLinks.size(); i++)
{
int a = 0;
Node currentNode = theNodes[downLinks[i]];
traverseInner(a, currentNode);
}
#ifdef EBUG
Utils::logStream << TAG << "leave traverse\n";
#endif
return this->totalPayoff;
}


Here is the traverseInner function



int Traversal::traverseInner(int& level, Node& node)
{
#ifdef EBUG
Utils::logStream << " " << TAG << "enter traverseInner" << node.toString() << endl;
#endif

std::vector<int> nodeDownLinks = node.getDownLinks();

if(nodeDownLinks.size() == 0)
{
totalPayoff = totalPayoff + node.getPayoff();
return 0;
}

for(int i = 0; i < nodeDownLinks.size(); i++)
{
int a = 0;
Node currentNode = theNodes[nodeDownLinks[i]]; <-- This causes segmentation error.
traverseInner(a, currentNode);
}

#ifdef EBUG
Utils::logStream << " " << TAG << "leave traverseInner\n";
#endif
return totalPayoff;
}


Any variables that are not declared here are declared in the header file. The code compiles fine.


I'd also like to mention that I have written this code in many different ways and through my observations have come to the conclusion that any variable that is trying to be accessed in the braces of a nested statement cannot be accessed by the memory. Even the int a variable that is declared right above the problem statement and even hard coded data which is supposed to be there such as nodeDownLinks. If I try to print out through standard output the size of the vector inside one of the nested statements, I also get a segmentation error.




Aucun commentaire:

Enregistrer un commentaire