Reputation: 1
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
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
:
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;
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:
input
to scanf
suffices; no need for &input
.Your scanf
is vulnerable to buffer overflows. Use
scanf("%s29", input);
instead. Read this also.
Upvotes: 4
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
Reputation: 167
You need to allocate memory for new_a
:
new_a = malloc(sizeof(ELEMENT));
Upvotes: 0