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