Gargamel
Gargamel

Reputation: 1

Linked list boilerplate code having trouble with type redefinitions

I've recently been getting into C. A project I'm currently working on requires the use of a linked list, so I sourced some boilerplate code. This code seems to be fairly standard, recurring on multiple sites. I however cannot seem to get it to work.

typedef struct node {
    int value;
    struct node * next;
} node_t;

node_t * head = NULL;
head = (node_t *)malloc(sizeof(node_t));

Results in the error messages

main.c:7:1: warning: type specifier missing, defailts to 'int'
head = (node_t *)malloc(sizeof(node_t));
^

main.c:7:1: error: redefinition of 'head' with a different type: 'int' vs 'node_t *' (aka 'struct node *')
main.c:6:10: note: previous defintion is here
node_t * head = NULL;
         ^

To me this looks like head failed to initialize as node_t *, and defaulted to an int. Why would this happen? How would you solve this? In case it matters im using Repl.it with clang-7.

Upvotes: 0

Views: 43

Answers (3)

tstanisl
tstanisl

Reputation: 14157

In old times C compilers let use functions without declaring them. Their return value defaults to int. You missed include of stdlib.h thus malloc is undeclared and returns int.

Upvotes: 0

Petr Skocik
Petr Skocik

Reputation: 60097

You can't have assignments (statements) in filescope. Put the malloc call in a function.

You might want to remove the (node_t*) cast too. It's bad practice in C, as it can hide a lack of malloc declaration (=> the file should include stdlib.h to get that declaration).

#include <stdlib.h>

typedef struct node {
    int value;
    struct node * next;
} node_t;

node_t * head = NULL;

int main(void)
{
    head = malloc(sizeof(*head));
}

gcc.godbolt.org/z/cssfzG

(To avoid conflicts with POSIX, you might also want to avoid names ending with _t: http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html.)

Upvotes: 0

0___________
0___________

Reputation: 67721

In C language all the code has to be in the function bodies.

#include <stdlib.h>

typedef struct node {
    int value;
    struct node * next;
} node_t;

node_t * head = NULL;

void foo(void)
{
    head = malloc(sizeof(*head));
}

Upvotes: 1

Related Questions