Is malloc/calloc evaluated at runtime?

Problem:

#include 
#include 

typedef struct {
    int x;
    int y;
} test;
test *tests = calloc(10, sizeof(*tests));

int main(int argc, char** argv){
  ...
  free(tests);
  return 0;
}

 

When I compile it, it gives error:
error: initializer element is not constant.

Solution:
After troubleshooting for a long time, eventually find out that it would work if I put the definition of tests in a function:

#include 
#include 

typedef struct {
  int x;
  int y;
} test;
test *tests;
test *allocation(){
  return calloc(10, sizeof(*tests));
}
int main(int argc, char** argv){
  tests = allocation();
  ...
  free(tests);
  return 0;
}

 

After hours thinking and research, I figured that malloc/calloc is evaluated during run time. But global variables and directives are evaluated during compile time.
Therefore, it has to be inside a function.
As the following article states, “malloc (memory allocation) is used to dynamically allocate memory at run time.”
http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/FUNCTIONS/malloc.html

Leave a Reply