DerekT
DerekT

Reputation: 1

unable to insert element into linked list

I am trying to write a program that finds all the ")" in an expression and puts them in a linked list, always adding at the beginning of the list. The problem is that when I try to place a new element into the list, the program stops working.

With a sample user input 865)987:

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

typedef struct element {
    char data;
    struct element *next;
} ELEMENT;


int main(void)
{
   ELEMENT *first = NULL;
   ELEMENT *new_a;

   char input[30];
   int x=0;

   printf("Input expression: ");
   scanf("%s", &input);

   while(input[x]!='\0'){
       if (input[x]==')'){
           printf("%c", input[x]);        //This works just fine.
           new_a->data = input[x];        //Here, the program stops working.
           new_a->next = first;
           first = new_a;
       }
       x++;
    }
}

What am I doing wrong?

Upvotes: 0

Views: 75

Answers (3)

cadaniluk
cadaniluk

Reputation: 15229

new_a->data

is equivalent to

(*new_a).data

As you can see, new_a is attempted to be dereferenced. The problem is that new_a is uninitialized, so any subsequent attempt to dereference it is undefined behavior (in shape of, e.g., a segmentation fault).

In order to fix this, you need to allocate memory for new_a:

  1. Allocate space on the stack. This will only work if the linked list is exclusively used in main because local variables' scope only embraces the beginning and end of a function.
    Do it like this:

    ELEMENT new_a;
    
    ...
    
    new_a.data = input[x];
    new_a.next = first;
    first = &new_a;
    
  2. Use malloc. This is usually used for linked lists and is applicable for a linked list existing till the very termination of your program because it's scope-independent:

    ELEMENT* new_a = malloc(sizeof(ELEMENT));
    

    Don't forget to free afterwards!


Notes:

Upvotes: 4

Anton Todua
Anton Todua

Reputation: 687

As previously answered, the correct code is:

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

typedef struct element {
    char data;
    struct element *next;
} ELEMENT;

int main(void)
{
    ELEMENT *first = NULL;  
    char input[30];
    int x=0;

    printf("Input expression: ");
    scanf("%s", &input);

    while(input[x]!='\0'){
        if (input[x]==')'){
            ELEMENT *new_a = (ELEMENT*)malloc(sizeof(ELEMENT));
            printf("%c", input[x]);
            new_a->data = input[x];
            new_a->next = first;
            first = new_a;
        }
        x++;
    }
}

Upvotes: 0

Programmer dude
Programmer dude

Reputation: 167

You need to allocate memory for new_a:

new_a = malloc(sizeof(ELEMENT));

Upvotes: 0

Related Questions