16
#include <stdio.h>
#include <stdlib.h>

struct NODE {
    char* name;
    int val;
    struct NODE* next;
};
typedef struct NODE Node;

Node *head, *tail;
head = (Node*) malloc( sizeof( Node ) ); //line 21

And I compiling like this:

cc -g -c -o file.tab.o file.tab.c

I'm getting this error message:

file.y:21:1 warning: data definition has no type or storage class [enabled by default]
0

4 Answers 4

36

It looks like the line

head = (Node*) malloc( sizeof( Node ) ); //line 21

is outside the main() function. You can't do that, because you can't execute code outside functions. The only thing you can do at global scope is declaring variables. Just move it inside the main() or any other function, and the problem should go away.

(PS: Take a look at this question on why you shouldn't type-cast malloc)

3
  • 1
    fought with this for an hour...so silly...now I'm embarrassed lol, thanks!!
    – mgrenier
    Jan 29, 2018 at 20:24
  • @streppel, I am getting the same error when I write dev_t dev; dev = MKDEV(300, 0), instead if I write dev_t dev = MKDEV(300, 0), my module runs fine. Why is that? What is the reason behind this?
    – Dr. Essen
    Feb 11, 2018 at 5:55
  • @Dr.Essen MKDEV is a macro. The result value is precomputed at compile time.
    – Robert
    Sep 18, 2020 at 3:55
2

Try putting the malloc and variable declarations in a main function, and delete the cast on malloc. It should look like this:

#include <stdio.h>
#include <stdlib.h>

int main(){

    struct NODE
    {
        char* name;
        int val;
        struct NODE* next;
    };

    typedef struct NODE Node;

    Node *head, *tail;
    head = malloc( sizeof(Node) ); //line 21
}
1
  • You probably want to move the struct definition (and its associated typedef) out of main, if you want them to be reusable by other parts of the project. Sep 19, 2013 at 23:14
2

The problem is that you're trying to call malloc when you aren't executing inside of a function. If you wrap that inside a main function, for example:

int main(int argc, char **argv)
{
    Node *head, *tail;
    head = (Node*) malloc( sizeof( Node ) );
    /* ... do other things ... */
    return 0;
}

… it works just fine. GCC's error is a little cryptic, but the problem is basically that you're trying to initialize a variable with something that isn't a constant, which is impossible outside of a function.

2

You need to put your code inside a function:

#include <stdio.h>
#include <stdlib.h>

struct NODE {
    char* name;
    int val;
    struct NODE* next;
};
typedef struct NODE Node;

main(){
    Node *head, *tail;
    head = (Node*) malloc( sizeof( Node ) ); //line 21
}

should work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.