c++ – Segmentation fault in Iterative node insertion in BST


/* The structure of a BST node is as follows:

struct Node {
    int data;
    Node *left;
    Node *right;

    Node(int val) {
        data = val;
        left = right = NULL;
    }
};

*/
Node* insert(Node* root, int Key)
{  
    if(root==NULL)
     {
    struct Node* temp= ( struct Node*)(malloc(sizeof(struct Node)));
    temp->data= Key;
    root=temp;
    }
   if(root!=NULL)
    {
       Node* r=root,t= NULL;
       while(r)
       {
           t=r;
           if(Key==r->data) return root;
           if(Key>r->data) r=r->right;
           if(Key<r->data) r=r->left;
       }
       struct Node* temp= ( struct Node*)(malloc(sizeof(struct Node)));
       temp->data= Key;
       if(Key>t->data) t->right= temp;
       if(Key<r->data) t->left= temp;
       
       
        }
    return root;
}

Please help me find the cause of segmentation fault in iterative solution to insert a node with given pointer to the root and value of the node, in a binary tree