In the following code the function addMid is used to add element in middle of a linked list, but it is only working fine if the number can be added.

if K exceeds the length of the linked list then it should be detected by the while loop, message should be displayed and the function stopped but somehow it is not, and thus throwing segmentation fault. Why is this so?

The function is working properly for 1<=K<=LengthOfLinkedList

```
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node* next;
};
Node* head=NULL;
void addBeg( int new_data){
Node* new_node = new Node();
new_node->data = new_data;
new_node->next=head;
head=new_node;
}
void addEnd(int new_data){
Node* new_node = new Node();
new_node->data=new_data;
new_node->next=NULL;
Node* ptr = new Node();
ptr=head;
while(ptr->next!=NULL){
//cout<<"here"<<ptr->data<<"\n";
ptr = ptr->next;
}
ptr->next = new_node;
}
void addMid(int new_data, int k){
Node* new_node = new Node();
new_node->data = new_data;
Node* ptr = new Node();
ptr=head;
if(k==1){
addBeg((new_data));
return;
}
int cnt=1;
while(cnt<k-1){
if(ptr==NULL || ptr==0 ){
cout<<"sorry less elements";
return;
}
ptr = ptr->next;
cnt++;
}
//cout<<"elem "<< ptr->data<<"\n";
new_node->next = ptr->next;
ptr->next = new_node;
//cout<<" "<<ptr->data<<"\n";
}
void printList(){
Node* ptr = new Node();
ptr=head;
while (ptr!=NULL){
cout << ptr->data <<" " ; //<<ptr->next<<"\n";
ptr = ptr->next;
}
}
int main()
{
cout << "Hello world!" << endl;
Node* Head=NULL;
addBeg(1);
addBeg(2);
addEnd(3);
addEnd(5);
addMid(7,6);
printList();
}
```