0
#include<stdio.h>
#include<malloc.h>

struct list {
    char name[30];
    char subject1[30];
    char subject2[30];
    struct list* next;
    struct list* previous;
};

typedef struct list node;

node input(node* n1)
{
    node n2;
    n2.previous=n1;
    n1->next=&n2;
    n2.next=NULL;
    scanf("%s",n2.name);
    scanf("%s",n2.subject1);
    scanf("%s",n2.subject2);
    return n2;
}

void delete(node *n1)
{
    if(n1->next!=NULL)  
        n1->previous->next=n1->next;
    else
        n1->previous->next=NULL;
    if(n1->previous!=NULL)  
        n1->next->previous=n1->previous;
    printf("\nDeleting....");
    free(n1);
}

int main()
{
    node* start;
    start=(node*)malloc(sizeof(node));
    node n1=input(start);
    node n2=input(&n1);
    start->previous=NULL;
    printf("%s %s %s %s %s %s",n1.name,n1.subject1,n1.subject2,n2.name,n2.subject1,n2.subject2);
    delete(&n1);
    delete(&n2);
    delete(start);
    return 0;
}

The deletion is not happening properly. It's giving an unhandled exception returning 255 error. Also, in books only the n1 node is being deleted and the start(header) and last node is being left as it is. But, I want to delete all the nodes and header. Please explain and correct. Also, I am writing this code in C and C++. Please correct accordingly.

WedaPashi
  • 3,561
  • 26
  • 42
  • `` is deprecated (and linux-specific), use `` instead. – WedaPashi May 30 '18 at 07:11
  • Typecasting at `(node*)malloc(sizeof(node));` is needless. Read more on this at [Do I cast the result of malloc?](https://stackoverflow.com/q/605845/4228131) – WedaPashi May 30 '18 at 07:12
  • I did that. But, it doesn't solve my problem. – Debasrito Lahiri May 30 '18 at 07:16
  • Your program has undefined behavior because you assign the pointer to a local variable to your `start` node, and then attempt to deference that later. – jxh May 30 '18 at 08:16
  • You need to allocate node in your input function. Also, you dereference n1->previous (i.e. n1->previous->next) which may also be NULL, but check for it afterwards. All your node objects should be pointers, otherwise you are calling free on an object that is on the stack. – Lloyd Macrohon May 30 '18 at 09:45
  • Thanks. I just had to check for both n1->previous and n1->next whether they were null or not together I.e && both condns. in one if. I also had to add another line for n1->next!= NULL condn. That did it. I will give the new corrected code below if possible. – Debasrito Lahiri Jun 01 '18 at 12:48

0 Answers0