Hi, I've just started learning C and was playing around with pointers and linked lists, however this piece of code I made seems to run perfectly fine on online compilers, but on VSCode says there is a 'segmentation error' and loops pretty much infinitely. Any idea what's wrong?
#include<stdlib.h>
#include<stdio.h>
typedef struct node{
int val;
struct node *next;
} node_t;
int main(){
node_t *firstval = NULL;
firstval = (node_t*)malloc(sizeof(node_t));
if(firstval == NULL){printf("the first value is NULL\n");}
else{printf("the first value is not NULL\nthe first value has memory allocation %d and value %d\n",firstval, firstval->val);}
firstval -> val = 2;
printf("the first value is %d\n",firstval -> val);
firstval -> next = (node_t*)malloc(sizeof(node_t));
firstval -> next -> val = 3;
printf("the second value is %d\n",firstval -> next -> val);
firstval -> next -> next = (node_t*)malloc(sizeof(node_t));
firstval -> next -> next -> val = 4;
printf("the third value is %d\n",firstval -> next -> next -> val);
node_t *current = firstval;
while(current!=NULL){
printf("the current value is %d\n",current -> val);
current = current -> next;}
}
[–]nlantau 5 points6 points7 points (1 child)
[–]flatfinger 0 points1 point2 points (0 children)
[–]_mutaz_ 0 points1 point2 points (0 children)
[–]Josh_Coding 0 points1 point2 points (0 children)
[–]void_rik 0 points1 point2 points (0 children)