循环中获取分段错误

时间:2015-11-26 12:45:08

标签: c++ loops segmentation-fault

我对此代码有疑问:

while(true){
    BCNP(CBCV[CBCV.size()-1]);
    CBCV.pop_back();
    printf("BCN : %f\n", BCN());
    for(int q = 0; q < numNode; q++){
        CurrentNode = ((MobileNode*)Node::get_node_by_address(q));
        if(CurrentNode->ConditionNeighbor == BCN()){
            printf("currentnode : %f\n", CurrentNode->ConditionNeighbor);
            tcl.evalf("$ns_ at %f \"$node_(%d) color red\"",NOW,CurrentNode->nodeid());
            tcl.evalf("$ns_ at %f \"$node_(%d) label \\\"CH\\\"\"",NOW,CurrentNode->nodeid());
            break;
        }
    }
    CurrentNode->isCluster = true;
    for(int q = 0; q < CurrentNode->NodeQueue; q++){
        neighbor = ((MobileNode*)Node::get_node_by_address(CurrentNode->neib[q]));
        //if(neighbor->isCluster == false){
            neighbor->chFlag = true;
            CurrentNode->chFlag = true;
            neighbor->cluster = CurrentNode->nodeid();
            //printf("chFlag True : %d\n", neighbor->nodeid());
        //}
    }
    notRouted_ = 0;
    for(int q = 0; q < numNode; q++){
        CurrentNode = ((MobileNode*)Node::get_node_by_address(q));
        if(CurrentNode->chFlag == false){
            notRouted_++;
            //printf("CurrentNode : %d\n",CurrentNode->nodeid());
        }
    }
}

它给了我一个分段错误,但我不知道我在哪里遗漏了什么......

似乎没有定义变量,并且在循环中它会使用该变量,这就是我收到此错误的原因...
我昨晚完全没有睡觉,现在我的思绪正在关闭,我真的需要帮助。

如果有人给我一个关于这个错误的想法,那将是最好的。

    void            BCNP(double bcneighb){ BCN_ = bcneighb; };<br/>
    inline double   BCN(){ return BCN_; };
    inline int32_t  notRouted(){ return notRouted_; };
    int32_t numNode;
    std::vector<nsaddr_t> clusters;
    std::vector<double> CBCV; // __Could Be Cluster Vector
    double BCN_; // __Biggest Condition Neighbor
    int32_t notRouted_; // __number of nodes that have no cluster
    // CurrentNode is a class
    bool chFlag; // in CurrentNode
    double ConditionNeighbor; // CurrentNode
    numNode = 80;
    notRouted_ = 0;
    BCN_ = 0;

1 个答案:

答案 0 :(得分:0)

在更改nullptrCurrentNode之后添加对neighbor的检查

像:

CurrentNode = ((MobileNode*)Node::get_node_by_address(q));
if (CurrentNode == nullptr)
{
    cout << "Real bad version 1..." << endl;
}
else
{
    // Your normal code...
    if(CurrentNode->ConditionNeighbor == BCN()){
        printf("currentnode : %f\n", CurrentNode->ConditionNeighbor);
        tcl.evalf("$ns_ at %f \"$node_(%d) color red\"",NOW,CurrentNode->nodeid());
        tcl.evalf("$ns_ at %f \"$node_(%d) label \\\"CH\\\"\"",NOW,CurrentNode->nodeid());
        break;
    }
}

然后,您将发现错误,以便取消引用nullptr。

每当更改指针时,请记住添加类似的代码。