简体   繁体   English

插入二叉搜索树时出现分段错误

[英]Segmentation fault upon insertion into binary search tree

I wrote the following code to insert into binary search tree which can have duplicate entries but i get segmentation fault for larger inputs like greater than 30 ....plz help!! 我写了下面的代码插入二进制搜索树中,该树可以有重复的条目,但是对于较大的输入(例如大于30 .... plz帮助),我遇到了分段错误! The duplicate entries are stored in the right branch of the node 重复的条目存储在节点的右分支中

#include<stdio.h>
#include<time.h>
#include<stdlib.h>

typedef struct vertex{

    int num;
    struct vertex* r;
    struct vertex* l;

} node;


void insert(node* T,int x)
{

    if(x < T->num)
    {
        if(T->l == NULL)
    {
        T->l = (node*)malloc(sizeof(node));
        T->l->num = x;
        printf("%4d ",x);
        return;
    }
        else
    {
        insert(T->l,x);
    }
    }

    else if(x >= T->num)
    {
        if(x == T -> num)

        if(T->r == NULL)
    {
        T->r = (node*)malloc(sizeof(node));
        T->r->num = x;
        printf("%4d ",x);
        return;
    }
        else
        insert(T->r,x);
    }

}



main()
{
    srand((unsigned int)time(NULL));

    int i,n,m,x;
    node* T;

    printf("n = ");
    scanf("%d",&n);
    printf("\nm = ",&m);
    scanf("%d",&m);

    printf("\n\n\n+++ Inserting %d random integers between 1 and %d\n",n,m);

    x = 1 + rand() % m;
    T = (node*)malloc(sizeof(node));
    T->num = x;
    printf("%4d (1)",x);

    for(i=1;i<n;i++)
    {
        x = 1+rand() % m;
        insert(T,x);
        if(i%8 == 7)
    printf("\n");

    }

    printf("\n\n");
}

malloc() does not initialize memory, so set other member to NULL after allocation or use calloc() . malloc()不会初始化内存,因此在分配后将其他成员设置为NULL或使用calloc() Without this you will be accessing random memory when you do T->l or T->r . 否则,当您执行T->lT->r时,您将访问随机存储器。

T = malloc(sizeof(node));
T->num = x;
T->l = NULL;
T->r = NULL;

or 要么

T = calloc(1, sizeof(node));
T->num = x;

Do this in all places where you use malloc() 在使用malloc()所有位置执行此操作

malloc(noofbytes) function only allocate noofbytes space only does not initialize with NULL .

This is the problem with your code. 这是您的代码的问题。

When you allocate memory 分配内存时

T->l = (node*)malloc(sizeof(node));
T->l->num = x;

you allocated memory of size of structure node but it is not initialized . 您分配了结构节点大小的内存,但尚未初始化。 Means 手段

T->l->l and T->l->r is not NULL and have some garbage value.

when you traverse it T->l== NULL or T->r==NULL condition not get satisfied and so it gives segmentation fault. 当您遍历它时,T-> l == NULL或T-> r == NULL条件得不到满足,因此会产生分段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM