Search code examples
cstaticdynamic-memory-allocation

Is it possible to intialise a static variable dynamically in c?


I know that a static variable must be initialized with a constant because the value of the static variable must be known before the program starts running.

So can we say that its not possible to initialize a static variable using dynamic memory allocation as that means that the variable will be initialized while the program is running.

Also can someone please explain why the value of the static variable must be known before main starts running?


Solution

  • Regarding your title question: Is it possible to intialise a static variable dynamically in c? The answer is no. Details of why below...

    The answer to your next question:

    "So can we say that its not possible to initialize a static variable using dynamic memory allocation..."

    is yes, we can say that, because:

    static int *array = calloc(5, sizeof(int)); 
    

    will fail to compile, as the initializer element is not a compile-time constant.

    The reason it will fail to compile is given in the C standard, N1570 paragraph 5.1.2 where it clearly states:

    All objects with static storage duration shall be initialized (set to their initial values) before program startup.

    However, dynamically allocating memory to a properly initialized static variable is legal:

    static int *array = NULL; //properly initialized static pointer variable.
    ...
    array = calloc(5, sizeof(int));// legal
    

    Answers to your final question: why the value of the static variable must be known before main starts running?

    can be derived from These statements...

    1. Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope. [emphasis mine]
    1. Static variables are allocated memory in data segment, not stack segment. See memory layout of C programs for details. [emphasis mine]
    1. Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage.[see link for referenced program]

    So, by definition, because variables with static storage duration exist during the entire life-time of the program, it makes sense that a known value exists in that memory space during the onset of run-time. (When main() starts running.)