c ++中奇怪的指针

时间:2018-02-20 04:00:48

标签: c++ pointers

什么会导致指针在c ++中看起来像这样?我正在为一个项目构建一个霍夫曼树,当我的节点是当前节点的一个子节点时,我的程序就是segfaulting。 childNode == NULL也无法检测到这一点。

(TreeNode *) 0x3130303030313131

编辑,按以下顺序调用以下函数:buildTree() -> generateCodes()

void HuffTree::buildTree(MinHeap * heap) {
    while (heap->getSize() > 1) {
        TreeNode * n1 = heap->removeMin();
        TreeNode * n2 = heap->removeMin();

        TreeNode * p = new TreeNode(0, (n1 != NULL ? n1->getFrequency() : 0) + (n2 != NULL ? n2->getFrequency() : 0));
    p->join(n1, n2);

        heap->insert(p);
    }

    root = heap->removeMin();
}

void HuffTree::generateCodesRecursive(TreeNode * node, int right, string code) {
    if (node == NULL) return;

    if (node->isLeafNode()) {
        codes[node->getVal()] = code;
        cout << (unsigned int) node->getVal() << " " << (int) node->getFrequency() << " " << code << endl;
    }

    generateCodesRecursive(node->getLeft(), 0, code + "1");
    generateCodesRecursive(node->getRight(), 0, code + "0");
}

void HuffTree::generateCodes() {
    generateCodesRecursive(root, 0, "");
}

编辑,堆函数:

void MinHeap::insert(TreeNode * val) {
    nodes.push_back(val);   

    int index = nodes.size() -1 ;
    while (nodes[parent(index)]->getFrequency() > nodes[index]->getFrequency()){
        swapNodes(index, parent(index));    
        index = parent(index);
    }
}

TreeNode * MinHeap::removeMin() {
    if (nodes.size() == 0) return NULL;

    TreeNode* minNode = nodes[0];

    if (nodes.size() > 0){
        TreeNode* lastNode = nodes[nodes.size()-1];
        nodes.pop_back();
        nodes[0] = lastNode;
    }

    int index = 0;
    while((left(index) < nodes.size() && nodes[left(index)]->getFrequency() < nodes[index]->getFrequency()) ||
    (right(index) < nodes.size() && nodes[right(index)]->getFrequency() < nodes[index]->getFrequency())) {
        int swapIndex = right(index) >= nodes.size() ? left(index) : (nodes[left(index)]->getFrequency() <= nodes[right(index)]->getFrequency() ? left(index) : right(index));

        swapNodes(swapIndex, index);
        index = swapIndex;
    }

    return minNode;
}

2 个答案:

答案 0 :(得分:2)

要牢记几件事。当你执行TreeNode* p;时,p将不会为空,并且会指向垃圾记忆,除非您明确将其设置为if (p == NULL)if (p == nullptr)条件,否则它将无法被null# NOTE : It's just a quick recipe that not verified in real production # # Compile and install Kannel 1.5.0 # tar jvxf gateway-1.5.0.tar.bz2 cd ./gateway-1.5.0 ./configure --prefix=/usr/local/kannel make make install # # Compile and install Mbuni 1.6.0 # cd .. tar zvxf mbuni-1.6.0.tar.gz cd mbuni-1.6.0 ./configure --prefix=/usr/local/mbuni --with-kannel-dir=/usr/local/kannel --disable-shared make make install 条件检测到初始化期间datatype

另外,您是否正确地在其构造函数中初始化TreeNode的内部数据成员?

答案 1 :(得分:1)

如果你有一些不是指针的数据并且你试图假装它是一个指针,你会得到这样一个无效的指针值。

获得此类指针的最可能方式是来自未初始化的指针变量。在C和C ++中,未初始化的变量(包括指针)可能包含不可预测的“随机垃圾”值。