簡體   English   中英

二進制搜索樹(C),插入功能中的分段錯誤

[英]Binary Search Tree (C), segmentation fault in Insertion function

我試圖在二叉搜索樹上創建一個插入函數。 我在這里查看了其他問題,但他們不喜歡我的問題。

我可以編譯它,但是它在下面的注釋行中崩潰:

void insertNode(TreeNode** r, int n) {

TreeNode* novono;

    novono = createNode(n);
    if (*r == NULL){ //corrected
        *r = novono;
        (*r) -> right = NULL;
        (*r) -> left = NULL;
        (*r) -> data = n;
    }
    if (n < ((*r) -> data))
        insertNode(&((*r) -> left), n); //SEGMENTATION FAULT HERE
    if (n > ((*r) -> data))
        insertNode(&((*r) -> right), n); //SEGMENTATION FAULT HERE

}

這是試圖從向量中插入整數的主要功能:

int main() {

#define MAX 15

TreeNode*   root    = NULL;
bool        OK      = true;
int         i       = 0, 
            n,
            V[MAX] = { 50, 10, 70, 2, 1, 13, 15, 65, 69, 77, 11, 3, 80, 76,   64}; 

    initTree(&root);
printf("Passou da inicialização");
    for ( i = 0 ; i < MAX ; i++ ) {
        printf("[%d] ", V[i]);

        insertNode(&root, V[i]);
        }

這是插入之前執行的初始化功能。 (我不認為這是問題,但我將其放在此處只是因為我知道您會要求它)。

void clearTree( TreeNode** r) {

    if ( *r != NULL) {
        printf("Clear %d\n", (*r)->data);
        clearTree(&(*r)->left);
        clearTree(&(*r)->right);
        free(*r);
        *r = NULL;
        }
}

void initTree( TreeNode** r) {

    if (*r != NULL)
        clearTree( &(*r) );

    if( *r == NULL)
        printf("Limpeza com sucesso !!\n"); 
    else    
        printf("Limpeza sem sucesso !!\n"); 
}

根據要求創建節點功能:

TreeNode* createNode(int n) {

    TreeNode* newNode = (TreeNode*) malloc(sizeof(TreeNode));

    if ( newNode != NULL) {
        newNode->data   = n;
        newNode->left   = 
        newNode->right  = NULL;
        }

    return newNode;
}

乍一看...“ if(* r = NULL)”應該是“ if(* r == NULL)”

從第二個角度看,我看不到崩潰,但是看到內存泄漏。 想想如果(* r == NULL)為false,在novono的同一函數中會發生什么。 我建議您忘記此代碼,並嘗試從頭開始再次編寫它,並盡量避免使用指向指針的指針-某些東西。

代替:

void insertNode(TreeNode** r, int n)

我會嘗試:

/* this error handling would be sufficient for the beginner */
void * xmalloc(size_t size) {
   void * ret = malloc(size);
   if (!ret) { 
      printf("error\n");
      exit(1); 
   }
   return ret;
} 

/* returns root of the tree */
TreeNode * insertNode(TreeNode* r, int n) {
   if (!r) return createNode(n);
   ...
   return r;
}

TreeNode * createNode(int n) {
   TreeNode * ret = xmalloc(sizeof(TreeNode));
   ret->left = left->right = 0;
   ret->data = n;
   return ret;        
}

代替initTree,只是:

....
TreeNode * root = 0;
root = insertNode(root, 10);
root = insertNode(root, 12);
root = insertNode(root, 20);
root = insertNode(root, 14);
if (n < ((*r) -> data));
    insertNode(&((*r) -> left), n);

等效於:

if (n < ((*r) -> data)) {
    ;
}
insertNode(&((*r) -> left), n);

所以很可能不是您想要的。

(帶有-Wempty-body (包含在-Wextra )的GCC會警告您。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM