Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 740
ratzip Avatar asked May 02 '26 19:05

ratzip


1 Answers

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.

like image 198
Sourav Ghosh Avatar answered May 05 '26 10:05

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!