2012-07-24 6 views
0

지금까지 허프만 코딩 프로그램을위한 노드의 이진 트리를 생성하는 프로그램을 만들었습니다. 어떤 이유로, 디버거가 두 자식이 Null인지 아닌지를 테스트 할 때 (실제로 부모가 아닌 실제 문자가 있기 때문에) 프로그램이 멈 춥니 다. 코드는 두 개의 멤버 변수가있는 코드 구조체로 구성된 각 객체의 코드 배열입니다.멤버 변수가 NULL인지 여부를 테스트 할 때 C++이 멈 춥니 다

void Huff::traverse(Node* root, vector<Code>* code, string code_base){ 
    if(root->childL == NULL && root->childR == NULL){ //stops here 
     Code c; 
     c.content = root->litteral; 
     c.symbol = code_base; 
     code->push_back(c); 
    }else{ 
     if (root->childL != NULL) 
      traverse(root->childL, code, code_base + '0'); 
     if (root->childR != NULL) 
      traverse(root->childR, code, code_base + '1'); 
    } 
} 

이 하나가 호출하는 기능 (그것은 끝으로 불렀다) :

vector<Code>* Huff::compress(){ 
    //-------GETTING WEIGHTS/FREQUENCIES------ 
    vector<Node *>* nodes = new vector<Node*>; // Vector of nodes for later use 
    map<char, int>* freq = new map<char, int>; // Map to find weight of nodes 
    for(unsigned int i = 0; i < content.length(); i++) 
     (*freq)[content[i]]++; 
    CopyTo copyto(nodes); //sets vector<Node*> to copy to 
    for_each(freq->begin(), freq->end(), copyto); // Copies 
    delete freq; 
    vector<Node *>::iterator beg = nodes->begin(); 

    //-------SETTING UP TO BUILD TREE------ 
    if(nodes->size() % 2 == 1){ //makes sure there are an even number of nodes 
     Node* fill = new Node; 
     fill->set_node(0, '*', NULL, NULL); 
     nodes->push_back(fill); 
    } 
    huff_sort(nodes); // sort nodes by weight 

    //-------BUILDING TREE------ 
    while(nodes->size() != 1){ //Sorts nodes by weight and then removes two of them and replaces them with one 
     int w= (**beg).weight + (**(beg+1)).weight; 
     Node* p = new Node; 
     p->set_node(w, '*', *nodes->begin(), *(nodes->begin()+1)); //making it the parent node of the two lowest nodes 
     nodes->erase(nodes->begin(), nodes->begin()+2); 
     unsigned int i = 0; 
     while(w > (*nodes)[i]->weight && i <= nodes->size()){ //finds where to insert the parent node based on weight 
      i++; 
     } 
     if(i > nodes->size()) //if it needs to be inserted at the end 
      nodes->push_back(p); 
     else 
      nodes->insert(nodes->begin()+i, p); 
     delete p; 
    } 

    //-------TRAVERSING TREE------ 
    Node* root = (*nodes)[0]; 
    delete nodes; 
    vector<Code>* codes; 
    traverse(root, codes , ""); 
    delete root; 
    return codes; 
} 

주 : 나무가 생성되는 코드의 트래버스 나무 블록 전에 while 루프를

+1

프로그램이 멈추는 원인이되는 그 행에 대해서는 아무 것도 없습니다. 나는 더 많은 정보가 필요하다고 생각한다. 디버거에 액세스 할 수 없습니까? –

+0

루트가 유효합니까? 나는 아마 그렇지 않다고 말하고 싶다. –

답변

1

traverse으로 전화 한 후 delete nodes;라고해야합니다. 지금 가지고있는 것은 root이 을 가리 키기 전에 traverse으로 전화하십시오.

+0

그러나 노드는 노드에 대한 포인터 벡터의 포인터입니다. 벡터와 포인터 만 삭제 하겠지만 노드 자체는 삭제하지 않겠습니까? –

+0

아니요, 노드 자체가 * 포인터이므로 포인터가 가리키는 것을 삭제하기 때문입니다. – jrad

+0

기다림, 벡터 삭제가 끝나고 벡터 노드뿐 아니라 벡터 자체의 모든 포인터를 삭제합니까? –

1

root이 (if (root) ...)을 가리키고 있는지 확인하십시오. 도움이 될 것입니다.