【问题标题】:C - Null pointer issue on AVL tree rotation implementationC - AVL 树旋转实现上的空指针问题
【发布时间】:2013-05-06 09:07:19
【问题描述】:

我正在用 C 语言实现 AVL 树。我在下面发布了我的树旋转,以及我在尝试测试它们时遇到的 valgrind 错误。

为什么会出现这些错误?我知道 valgrind 错误源于我使用空指针这一事实,但我无法准确指出我做错了什么。 (我已经评论了 Valgrind 错误的行)

Tree rotateRight(Tree t)
{
    Tree temp = t->L;
    t->L=temp->R;
    temp->R=t;
    temp->height=maximum(heightT(temp->L), heightT(temp->R));
    t->height=maximum(heightT(t->L), heightT(t->R));
    return t;
}

Tree rotateLeft(Tree t)
{
    Tree temp = t->R; //This is line 226
    t->R=temp->L;
    temp->L=t;
    temp->height=maximum(heightT(temp->L), heightT(temp->R));
    t->height=maximum(heightT(t->L), heightT(t->R));
    return t;
} 

Tree rotateLeftRight(Tree t)
{
    t->L=rotateLeft(t->L); //Line 235
    t=rotateRight(t);
    return t;
}

Tree rotateRightLeft(Tree t)
{
    t->R=rotateRight(t->R);
    t=rotateLeft(t);
    return t;
}

Valgrind 错误(我在 rotateLeft 中得到了同样的结果):

==20073== Invalid read of size 8
==20073==    at 0x40196F: rotateLeft (bst.c:226)
==20073==    by 0x401A11: rotateLeftRight (bst.c:235)
==20073==    by 0x4013A9: insertT (bst.c:69)
==20073==    by 0x400E77: addin (Spell13.c:96)
==20073==    by 0x400CBE: main (Spell13.c:59)
==20073==  Address 0x10 is not stack'd, malloc'd or (recently) free'd
==20073== 
==20073== 
==20073== Process terminating with default action of signal 11 (SIGSEGV)

【问题讨论】:

  • inset()addin() 的代码也会有所帮助。

标签: c tree valgrind avl-tree null-pointer


【解决方案1】:

获取您拥有的代码 + 错误报告,看起来好像 Tree 看起来像这样:

typedef struct Tree_s
{
    struct Tree_s *L;
    struct Tree_s *R;
} Tree;

看起来传递给rotateLeftRightTree->LNULL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多