0

エントリが重複する可能性のあるバイナリ検索ツリーに挿入する次のコードを作成しましたが、30 を超えるような大きな入力に対してセグメンテーション違反が発生します ....plz help!! 重複したエントリはノードの右側のブランチに格納されます

#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");
}
4

2 に答える 2

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

これはあなたのコードの問題です。

メモリを割り当てるとき

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

構造ノードのサイズのメモリを割り当てましたが、初期化されていません。意味

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

それをトラバースすると、 T->l== NULL または T->r==NULL 条件が満たされないため、セグメンテーション違反が発生します。

于 2013-09-16T08:40:04.367 に答える