Search code examples
cdynamic-memory-allocationstatic-variables

can we dynamically allocate memory for static variable in C?


Is it allowed to dynamically allocate memory for static variable like this:

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

struct person
{
   int age;
   int number;
};

static struct person* person_p = NULL;

int main()
{
    person_p = (struct person*)malloc(10 * sizeof(struct person));
}

The above code built, but is it really allowed to dynamically allocate memory for static variable?


Solution

  • Yes, it's valid and allowed. (Unless you're using the pointer as a placeholder) You can (and need to) dynamically allocate and free() memory to and from the pointer before and after using it.

    Rather, please make a note, you do not cast the return value of malloc() and family in C.