C malloc - Initializer element is not a compile-time constant

Viewed 46

I am just learning C. I'm trying to compile this code:

int *p = malloc(sizeof(int));

linked-list.c:12:10: error: initializer element is not a compile-time constant int *p = malloc(sizeof(int)); ^~~~~~~~~~~~~~~~~~~ 1 error generated.

What am I doing wrong here? I'm guessing it is talking about int not being a compile-time constant. Is that because it doesn't know the size of an int on my system? Most of the other answers on sa for this question seem like they really are using run-time variables as initializers but why is int a run time variable?

1 Answers

You can't initialize global variables with non-constant values. Do the initialization inside a function.

int *p;

int main(void)
{
    p = malloc(sizeof(int));
    free(p);
    return 0;
}
Related