Error, linked lists using C programming

79 Views Asked by At

I'm trying to code simple push function and everything is fine until run time, executed code crashes. Anyone can clarify the reason, please ?

#include<stdio.h>
#include<stdlib.h>

typedef struct list{
int order;
struct list *next;

}list;

void push(struct list **arg,int i);

int main()
   {
struct list **ptr=NULL;

for(int i=0;i<10;++i){
    push(ptr,i);
  }

return 0;
     }

void push(struct list **arg,int i){

 struct list *temp;
 temp= malloc(sizeof(list));

temp->order=i;

temp->next=*arg;

*arg=temp;

}
1

There are 1 best solutions below

4
On BEST ANSWER

Write

list *ptr=NULL;
     ^^^           
for(int i=0;i<10;++i){
    push( &ptr,i);
         ^^^^
  }

Otherwise if to declare like this

struct list **ptr=NULL;

then this dereferencing

*ptr

results in undefined behavior.