c - Some misconception with linked list implementation -


it seems have major misconception how can implement linked list in c. far can understand (and code simplified can be!), should work, instead returns segmentation fault. worth noting if comment out below marker, seems working, there underlying issue makes faulty.

#include <stdio.h> #include <stdlib.h>   typedef struct node {     int val;     struct node *next; } node;   int main (void) {     node *pode;     node *nx, *vx, *sx;      pode = (node *) malloc(1 * sizeof(node));     pode->val = 12;      pode = (node *) realloc(pode, 2 * sizeof(node));     pode->next = (pode + 1);     (pode + 1)->val = 66;      pode = (node *) realloc(pode, 3 * sizeof(node));     pode->next = (pode + 2);     (pode + 2)->val = 33;      pode = (node *) realloc(pode, 4 * sizeof(node));     pode->next = (pode + 3);     (pode + 3)->val = 44;       printf("%d\n", pode->val);      nx = pode->next;     printf("%d\n", nx->val);      // marker     vx = nx->next;     printf("%d\n", vx->val);      sx = nx->next;     printf("%d\n", sx->val);      return 0; } 

where's boo-boo?

well, first mistake using realloc(). that's easy burned because might or might not move node, causing pointers become dangerous dangling pointers.

linked lists linking nodes pointers, there's no reason reallocate 1 node larger node, , defeats ability splice list changing pointers. generally, you'd allocate each node separately. (in cases program might deallocate list nodes putting them "free" list fast deallocation , later reallocation.)

your second mistake forgetting set each node's next pointer allocate node. don't rely on allocator clear it.

even if code did set next pointers correctly, realloc() may move node, breaking pointers.

finally, if step through running program in debugger (e.g. clion), you'll able see have dangling pointers.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -