如何调试此Segfault

时间:2014-07-30 07:28:44

标签: c++ debugging segmentation-fault

我不允许删除对象吗?这就是为什么它会出现段错误,我可以使用下面的自我引用类,还是应该使用它? 高级谢谢

我实际上还是试图建立一个仍处于起步阶段的特里

 #include <iostream>
 #include <string>

 using namespace std;
 #define NUMCHAR 26

typedef struct t_struct{
    bool iscomplete;
    t_struct * val[NUMCHAR];
};



class t_tree
{
private:
    bool iscomplete;
    t_tree * val[NUMCHAR];
public:
    t_tree* init(t_tree* node);
    void uninit(t_tree* node);
    t_tree* add_word(t_tree * node , const char* str);
    bool find_word(t_tree *node , const char* str);
};


t_tree* t_tree :: init(t_tree* node)
{
    cout << "Enter Initilized " << endl;
    if(node == NULL) node = new t_tree;
    node->iscomplete = false;
    for(int i = 0 ; i < NUMCHAR ; i++) node->val[i] = NULL;

    cout << "Node Initilized " << endl;
    return node;
}

void t_tree :: uninit(t_tree* node)
{
    cout << "Here  " <<node << endl;
    if(node == NULL) return;


    for(int i = 0 ; i < NUMCHAR ; i++) uninit(node->val[i]) ;

    cout << "Here deleted  " <<node << endl;
    delete node;
    cout << "Here deleted  " <<node << endl;
    node = NULL;
    cout << "Node Uninitilized " << endl;
}


t_tree* t_tree :: add_word (t_tree* node,const char* str)
{
    if (str[0] == '\0')  node->iscomplete = true;

    else{
    unsigned int ch = str[0] - 'a';
    if (node->val[ch] == NULL) node->val[ch] = init(node->val[ch]);
    str++;
    add_word(node->val[ch],str);
    }

return node;
}

int main()
{
    t_tree root;
    root.init(&root);
    root.uninit(&root);
    return 0;

}

2 个答案:

答案 0 :(得分:3)

您在delete中尝试t_tree* node uninit(),但您的t_tree* node实际上是&root,这不是堆对象,因此您无法打电话给delete

答案 1 :(得分:0)

你的基本错误是不了解堆和堆栈之间的区别。

许多语言只对这样的对象使用堆,并且可以在它们上调用删除(或类似的,如Dispose())(但是,即使这样,这些语言通常使用new关键字来创建这样的对象)。

在这里,您试图在堆栈上分配的对象上调用delete堆操作。根本不允许这样做。

这是C ++中的一个基本概念,它对学习它非常重要。