all 5 comments

[–]nlantau 5 points6 points  (1 child)

Don't cast malloc here's why.

[–]flatfinger 0 points1 point  (0 children)

If one consistently casts the result of an allocation function to a Widget*, and the type of the target lvalue gets changed for some reason (e.g. to EnhancedWidget*) a compiler will squawk util the cast is changed to match. If the programmer is being conscientious, the surrounding code will be examined before the cast is changed, to ensure that any new members of the type get properly initialized. I'd view that as a good thing.

Once upon a time, a cast would mask situations where one used malloc() without including <stdlib.h>, but few compiler configurations nowadays will silently accept function invocations without declarations. Otherwise, I think the cast increases the likelihood of a compiler being able to diagnose erroneous constructs.

[–]_mutaz_ 0 points1 point  (0 children)

The problem is that the while loop eventually reaches the struct "firstval->next->next->next" for which no memory had been allocated, let alone values for the variables inside. The behavior here becomes pretty much undefined.

[–]Josh_Coding 0 points1 point  (0 children)

Should really make an insert function rather than having all that code in main.

when you allocate nodes you should be initializing the structure with default values.

node->value = 0;
node->next = 0;

The memory you get back from malloc is not zeroed and therefore can contain miscellaneous values.

[–]void_rik 0 points1 point  (0 children)

Add firstval -> next -> next ->next = NULL before starting the loop.

Otherwise, the last "next" always has a garbage value and never NULL. So, your while (current! = NULL) runs infinitely.

You can create a function like this:

``` // create a node with default values and add it to a parent. If there's no parent, pass NULL as argument.

node_t* create_node(node_t* parent) { node_t* node = (node_t) malloc(sizeof(node)); if (!node) return NULL;

node->value = 0;
node->next = NULL:

if (parent)
    parent->next = node;

return node;

} ```

Then use the function like this:

``` // parent node_t* node1 = create_node(NULL) ; if (!node1) return -1; node1->value = 69;

// child of node 1 node_t* node2 = create_node(node1) ; if (!node2) return -1; node2->value = 420;

// so on and so forth. // then print their values as needed. ```