Home > Blockchain >  Creating a linked list with random values
Creating a linked list with random values

Time:10-21

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

CodePudding user response:

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

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

CodePudding user response:

This declaration

struct el* head;

declares an uninitialized pointer that has an indeterminate value. So the following statement

head -> data = -150;

invokes undefined behavior.

Also using the magic number -150 in this statement does not make a sense.

The function can be defined the following way

struct el * RandList( size_t n )
{
    enum { MIN_VALUE = -50, MAX_VALUE = 150 };

    struct el *head = NULL;

    srand( ( unsigned int )time( NULL ) );

    for ( struct el *current, *new_el; 
          n-- && ( new_el = malloc( sizeof( struct el ) ) )!= NULL; )
    {
        new_el->data = rand() % ( MAX_VALUE - MIN_VALUE   1 ) - MIN_VALUE;
        new_el->next = NULL;

        if ( head == NULL )
        {
            head = new_el;
            current = head;
        }
        else
        {
            current->next = new_el;
            current = current->next;
        }
    }

    return head;
}
  • Related