【问题标题】:Struct causing segmentation fault导致分段错误的结构
【发布时间】:2014-12-27 05:10:55
【问题描述】:

我无法解决这个错误。我正在 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 时,我会立即遇到段错误。

为了进一步说明,这里是 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;

【问题讨论】:

  • 我建议删除行号。 :)
  • @G.Samaras 好的,如果分散注意力,我会删除它们。

标签: c segmentation-fault red-black-tree


【解决方案1】:

在进行 IS_RED 检查之前,您要确保右孩子和左孩子存在: 替换

if (is_red(root->right) && !is_red(root->left)) //is_red is giving me seg fault

if (root->right && is_red(root->right) && root->left && !is_red(root->left)) 

请也对其他地方进行类似检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 2012-03-09
    相关资源
    最近更新 更多