Search code examples
clinked-listinitializationsingly-linked-listfunction-definition

Creating a linked list with random values


I am facing issues while solving the following task:

"Write a C function RandList(n) that, given as input a positive integer n: creates a (unidirectional) linked list L of n elements; each element of the list contains a random integer value between -50 and 150 • RandList() returns L"

The code I have been writing so far is this one:

struct el{
  int data;
  struct el* next;
};


struct el* RandList(int n){
   srand( (unsigned) time(NULL));
   int i;
   struct el* head;
   head -> data = -150;
   struct el* p;
   for (i=0;i<n;i++){
     struct el* temp = malloc(sizeof(struct el));
     temp -> data =(rand()%200-50);
     temp -> next = NULL;
     if (head->data == -150){
       head = temp;
     }
     else{
       p=head;
       while (p->next != NULL){
     p=p->next;
       }
       p->next = temp;
     }
   
   
   }
   
   return head;

}
   
  

int main(){
  
  struct el* head = RandList(4);
  printf("%d\n", head -> data);
}

Though after the execution I run into a segmentation fault error. The problem seems to be related to p=head since if I simply write:

struct el* RandList(int n){
   srand( (unsigned) time(NULL));
   int i;
   struct el* head;
   head -> data = -150;
   struct el* p;
   for (i=0;i<n;i++){
     struct el* temp = malloc(sizeof(struct el));
     temp -> data =(rand()%200-50);
     temp -> next = NULL;
     if (head->data == -150){
       head = temp;
     }

In the body of the function (adding the correct brackets), the execution of the main runs fine. I do not understand why I get a segmentation fault, though


Solution

  •       struct el* head;
          head -> data = -150;
    

    head does not point anywhere valid. It's illegal to change whatever (???) it points to.