Liu
Liu

Reputation: 433

Memory leaked in C

The code doesn't work until I dynamically allocate the memory for pointer C in merge_List function.

If I uncomment list c = (list)malloc(sizeof(Node)); and comment list c;, the code works. I don't know why. Can anyone explain to me? The code is very straightforward, so not much comment. Thank you!

#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
   struct Node *next;
   int value;
}Node,*list;
list create_Node()
{  
   list head = (list)malloc(sizeof(Node));
   if(!head) exit(-1);
   list tail = head;
   int len;
   int val;
   printf("Please enter the length of the list:\n ");
   scanf("%d",&len);
   for(int i=0;i<len;i++)
   {
      list new = (list)malloc(sizeof(Node));
      if(!new) exit(-1);
      printf("Please enter the value of the node:\n ");
      scanf(" %d",&val);
      new->value=val;
      tail->next= new; 
      tail =new;
   }
   return head;
}

list merge_list(list a, list b)
{
    if(a==NULL||b==NULL) exit(-1);
    //list c = (list)malloc(sizeof(Node));
    list c;
    list d = c;
    while(a&&b)
    {
       if(a->value<=b->value)
       {
          c->next=a;
          c=a;
          a=a->next;
       }
       else
       {
          c->next = b;
          c=b;
          b=b->next;
       }
     }
     c->next = a?a:b;
     return d;
}
int main() {

   list  l = create_Node();
   l=l->next;
   list j = create_Node();
   j=j->next;
   list n =merge_List(l,j);
   n=n->next;
   while(n)
   {
      printf("%d\n",n->value);
      n=n->next;
  }
  return 0;
}

Upvotes: 1

Views: 122

Answers (1)

Daniel
Daniel

Reputation: 854

It took a bit of inspection, but this is the struct's type is

list {aka struct Node *}

According to the compiler. In other words, list is a pointer, and calling malloc will allocate memory for the pointer.

You did this before in your function create_Node(), on the line right after

list head = (list)malloc(sizeof(Node));

If you don't do this, you're performing actions on an uninitialized pointer, which is undefined behavior and shouldn't work since you don't clearly have a spot in memory you're using.

What malloc specifically does in this context, will allocate the sizeof a Node's bytes, and return a void pointer, which you cast to a list (or Node *). List will no longer be uninitialized and no longer has undefined behaviour, which is why it works.

Upvotes: 1

Related Questions