0
我在處理這個錯誤時遇到了問題。我實現在C紅黑樹和正在運行到分段錯誤在特定的位置(第29行)引起分段錯誤的結構
TNODE *tree_add(TNODE *root, const KEY k, const VALUE v) {
LNODE *lnode = NULL;
if (root == NULL) {
TNODE *node = talloc(k);
lnode = lalloc(v);
node->head = lnode;
node->tail = lnode;
node->is_red = true;
return node;
}
if (strcmp(k, root->key) < 0) {
root->left = tree_add(root->left, k, v);
} else if (strcmp(k, root->key) > 0) {
root->right = tree_add(root->right, k, v);
} else {
if (strcmp(k, root->key) == 0) {
lnode = lalloc(v);
root->tail->next = lnode;
root->tail = lnode;
root->tail->next = NULL;
}
}
if (is_red(root->right) && !is_red(root->left)) { //is_red seg faulting
root = rotate_left(root);
}
if (is_red(root->left) && is_red(root->left->left)) {
root = rotate_right(root);
}
if (is_red(root->left) && is_red(root->right)) {
flip_colors(root);
}
return root;
}
這裏是is_red
功能:
bool is_red(const TNODE *h) {
bool is_red = h->is_red;
return is_red;
}
實施之前最後三個if語句將BST轉換爲RB樹,代碼工作正常。奇怪的是,當我調試is_red
時,變量is_red
出現爲true
。這意味着我沒有訪問受限制的內存。但是,一旦我從is_red
函數返回,並且進入tree_add
,我會收到一個seg錯誤。
爲了進一步澄清,這裏是TNODE結構:
typedef struct tnode {
KEY key; // Search key for this binary search tree node.
struct tnode *right; // Right child.
struct tnode *left; // Left child.
LNODE *head; // Head of the linked list storing the values for the search key.
LNODE *tail; // Tail of the linked list storing the values for the search key.
bool is_red; // Flag use only in red-black trees to denote redness.
} TNODE;
我建議刪除行號。 :) – gsamaras 2014-10-30 23:35:25
@ G.Samaras好的,我會刪除它們,如果它分心。 – mrQWERTY 2014-10-30 23:36:25