In the following code,

```
#include <cstdio>
#include <cstdlib>
using namespace std;
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// finding head
ListNode *current = head, *previous = NULL, *start = head, *temp, *distinct;
// if(current->next != NULL && current->val == current->next->val) {
// }
if(current == NULL) return NULL;
while((previous!=NULL && previous->val == current->val) || (current->next!=NULL && current->next->val == current->val)) {
previous = current;
current = current->next;
if(current == NULL) return NULL;
}
head = current;
// delting all nodes from [start, head)
current = start;
while(current != head) {
temp = current;
current = current->next;
free(temp);
}
/* deleting the nodes which have duplicates */
distinct = head;
while(distinct->next != NULL && distinct->next->next != NULL) {
if(distinct->next->val == distinct->next->next->val) {
while(distinct->next != NULL && distinct->next->next != NULL && distinct->next->val == distinct->next->next->val) {
temp = distinct->next;
distinct->next = distinct->next->next;
free(temp); // LINE 68 <<<------------------------------------------------
}
temp = distinct->next;
distinct->next = distinct->next->next;
free(temp);
}
else distinct = distinct->next;
}
return head;
}
};
void printlist(ListNode* head) {
while(head != NULL) {
printf("%d ",head->val );
head = head->next;
}
}
int main(int argc, char const *argv[])
{
ListNode n1 = ListNode(1);
ListNode n2 = ListNode(2);
ListNode n3 = ListNode(2);
ListNode *head = &n1;
head->next = &n2;
head->next->next = &n3;
Solution obj;
head = obj.deleteDuplicates(head);
printlist(head);
return 0;
}
```

At line 68 : free(temp) , My program is throwing a segmentation fault , although the statement looks completely fine to me. Please help.

On using gdb , I get this following error

Program received signal SIGSEGV, Segmentation fault.

_int_free (av=0x7ffff7acf760 <main_arena>, p=0x7fffffffdcb0, have_lock=0) at malloc.c:3960

3960 malloc.c: No such file or directory.

(gdb) where

#0 _int_free (av=0x7ffff7acf760 <main_arena>, p=0x7fffffffdcb0, have_lock=0) at malloc.c:3960

#1 0x00000000004009cb in Solution::deleteDuplicates (this=0x7fffffffdca7, head=0x7fffffffdcb0) at leetcode.cpp:68

#2 0x0000000000400810 in main (argc=1, argv=0x7fffffffddc8) at leetcode.cpp:101