cgccinitializationstatic-memory-allocation

Error when initializing global pointer to dynamic memory


I was writing a program that involves malloc to create a global array. I tried this (outside main(), of course):

int *arr=malloc(5*sizeof(int));

In the GCC compiler, the following error is flashed:

main.c:4:10: error: initializer element is not constant
 int *arr=(int *)malloc(5*sizeof(int));
          ^

I tried this on Dev-C++, but no such error interrupted the compilation. What is meant by the error and why is it specific to GCC?


Solution

  • Variables declared at file scope must have initializers that are compile time constants. A function call is considered executable code and cannot exists outside of a function.

    The best way to handle this would be to initialize the pointer to NULL and perform the malloc in the main function.

    The reason you're not seeing an error with DEV-C++ is because it is a C++ compiler and C++ allows file scope variables to be initialized with function calls.