memory - C Segmentation Fault (core dumped) Linked List -


i keep getting segmentation fault (core dumped) run time error , can't figure out why.

my code:

struct node {     void *next;     void *val; }; typedef struct node* nodeptr;  struct list {     nodeptr head; }; typedef struct list* listptr;  listptr create() {     listptr ptr = malloc(sizeof(struct list));      return ptr; }  int insert(listptr list, void *obj) {     nodeptr newobj = malloc(sizeof(struct node));      //cast next self referencing node     newobj->next = (nodeptr) newobj->next;      //point beginning of list     nodeptr current = list->head;      if(list->head == null)     {         newobj->val = obj;         list->head->next = newobj;         newobj->next = null;          return 1;     }      return 0; }  int main(int argc, char *argv[]) {     int x = 2;     int *p = &x;      listptr thing = create();      insert(thing, p);      return 0; } 

the error here: list->head->next = newobj after debugging. thought had allocate memory list->head->next, when added code in still gave me same error. casting wrong or not allocating memory correctly? appreciated, thanks!

just put together, runs fine.

#include <stdlib.h> #include <stdio.h>   struct node {         void *next;         void *val; }; typedef struct node* nodeptr;  struct list {     nodeptr head; }; typedef struct list* listptr;  listptr createlist() {     listptr ptr = malloc(sizeof(struct list));     return ptr; }  void insert(listptr list, void *obj) {         // create , initialize new node     nodeptr newobj = malloc(sizeof(struct node));     newobj->val = obj;     newobj->next = null;      //point beginning of list     nodeptr curr = list->head;     // add node list     if(curr == null) // if no head node, make newobj head node     {         list->head = newobj;     }     else{ // otherwise traverse list until find last node (the 1 points null next)         while(1) {                 if(curr->next != null) {                         curr = curr -> next;                 } else {                         curr->next = newobj;                 }                 list->head = newobj;                 newobj->val = obj;                 list->head->next = newobj;                 newobj->next = null;         }     } } int main() {     int x = 2;     int *p = &x;      listptr thing = createlist();      insert(thing, p);      return 0; } 

Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -