Why this code give run error but on online gdb it give correct answer

#include
using namespace std;
struct node{
long long int data;
struct node *next;
};
struct node *p,*s;
void addtrail(node &head,long long int data){
node
n=new node;
n->data=data;
n->next=NULL;
if(head==NULL){
head=n;
p=n;
}
p->next=n;
p=n;

}
void merge(node *&head1,node *&head2,node *&head3){

if (head1->data <= head2->data) {
head3 = head1;
head1 = head1->next;
} else {
head3 = head2;
head2 = head2->next;
}
node *current = head3;
while (head1 != NULL && head2 != NULL) {
if (head1->data <= head2->data) {
current->next = head1;
head1 = head1->next;
} else {
current->next = head2;
head2 = head2->next;
}
current = current->next;
}
if (head1 == NULL) {
current->next = head2;
} else {
current->next = head1;
}

}

int main() {
long int h;
cin>>h;
for(long int l=0;l<h;l++){
long long int n;
cin>>n;
long long int a[n];
node *head1=NULL;
for(long long int i=0;i<n;i++){
cin>>a[i];
addtrail(head1,a[i]);
}
long long int m;
cin>>m;
long long int b[m];
node head2=NULL;
for(long long int i=0;i<m;i++){
cin>>b[i];
addtrail(head2,b[i]);
}
node
head3=NULL;
merge(head1,head2,head3);

node *u=head3;
while(u){
cout<data<<" “;
u=u->next;
}
cout<<”\n";
}
return 0;
}

This code is giving run time error because N1 and N2 could be zero and you have not accounted for that try adding if statements in the beginning of the merge function to check if either head1 or head2 is NULL.
Also you need to change the add train function else the code will give TLE when N1 or N2 will be equal to one because in that case the linked list formed will be circular.
Here is the rectified code : https://ide.codingblocks.com/s/171122

Hey @dineshjani, i hope i have cleared your doubt if you kindly mark the doubt as resolved. Thanks

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.