2013-06-22 44 views
0

我爲我的程序構建了一個二叉搜索樹。這是我的代碼:struct遞歸內存處理問題

struct node { 
    int steps; 
    int x; 
    int y; 
    struct node *left; 
    struct node *right; 
}*head; 

typedef struct node *Node; 

Node createStepsBinaryTree(Node head, int newStepsInt, int x, int y){ 
    if (head == NULL) { 
     head = (Node)malloc(sizeof(Node)); 
     if (head==NULL) { 
      return NULL; 
     }else{ 
      head->steps = newStepsInt; 
      head->x = x; 
      head->y = y; 
      head->left = head->right = NULL; 
     } 
    }else{ 
     if (head->steps > newStepsInt) { 
      head->left = createStepsBinaryTree(head->left, newStepsInt, x, y); 
     }else{ 
      head->right = createStepsBinaryTree(head->right, newStepsInt, x, y); 
     } 
    } 
    return head; 
} 

這是我從另一個調用遞歸函數此功能:

Coor insertDataToTree(Node stepsTree,Coor root, int x, int y, int map[length][length], int steps){ 

    steps++; 
    stepsTree = createStepsBinaryTree(stepsTree, steps, x, y); 
    . 
    . 
    . 

這是如何我就進入到遞歸函數:

Node stepsTree = NULL; 

root = insertDataToTree(stepsTree,root, startPoint.x, startPoint.y, map, startPoint.steps); 

現在我遇到的主要問題是: 它運行得非常好,前兩次運行,但第三次運行通過樹中的兩個結構,但它應該在什麼時候運行給自己一個NULL結構它給了一些真正接近NULL的東西。它顯示(節點*)0x000000000000000000001。

有誰知道我該如何阻止這種瘋狂? :)

+3

'head =(Node)malloc(sizeof(Node));'爲指針分配足夠的空間,指向整個結構。 (這個問題可能是由隱藏在typedef後面的指針造成的混淆造成的) – wildplasser

+0

如果你刪除(不必要的)'malloc()'的結果轉換,這是否會給你一個警告呢? – alk

+2

'sizeof(* head)'而不是'sizeof(Node)'可能更適合你。 – WhozCraig

回答

0
head = (struct node*)malloc(sizeof(struct node))

儘管sizeof(* Node)被大多數編譯器接受。

+0

好的...我嘗試了使用你的解決方案,它確實幫助了幾次運行,但過了一段時間它又發生了 –

+2

@ user1461635:或者更好的辦法是:'head = malloc(sizeof(* head));'然後它會問題是什麼「頭」指向。這種方式'malloc()** ** always **會分配正確的內存量,即聲明'head'指向的內容的大小。 – alk

2

正如@ wildplasser指出的那樣,您爲節點分配了足夠的空間,這是一個指針類型。您可能需要更改代碼,以便Node是一個結構或在malloc中分配sizeof(struct node)字節。

我強烈建議您不要將指針隱藏在typedef中 - 這是如何導致問題的幾個示例之一。

+0

我嘗試過使用吉爾伯茨的建議,但它只能幫助多跑幾次。經過一段時間,它又發生了...... –

+0

一旦你做出了這一改變,我看不到createStepsBinaryTree有什麼問題。問題可能與您的示例中省略的代碼有關。也就是說,insertDataToTree沒有第一次返回新樹的事實相當可疑。你如何通過該函數向樹添加多個節點? –