Can we dynamically allocate memory for a static variable in C?

Is it allowed to dynamically allocate memory for a 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 is built, but is it really allowed to dynamically allocate memory for a static variable?

+3


source to share


4 answers


Yes, it is valid and permitted. (If you don't use a pointer as a placeholder) You can (and should) dynamically allocate both free()

memory to and from a pointer before and after using it.



Rather, take a note, you are not putting the return value malloc()

and family in C.

+4


source


I don’t understand why not. Although static means can only be one instance of an object, you still need space for that object. Keep in mind that whatever is malloc

'd must be free

' d, so you'll want to do this at the end of your function main()

.



0


source


Memory is not "owned" by pointers to it. You can do the following:

  • Allocate memory dynamically
  • Make a pointer to this memory

It doesn't really make sense to say "dynamically allocate memory for a pointer".

Any pointer can point to any object (subject to alignment and anti-aliasing constraints), no matter how long the pointer is stored.

0


source


Note that this is a pointer that is static, not the memory it points to.

static

means two unrelated things:

  • provides static memory allocation (memory allocated at program startup and only released at the end of the program)
  • provide internal binding (do not allow other compilation units - modules - to access the identifier. Variable here can be a function)

In your code 1. static memory allocation doesn't matter as the variable is global and is already there anyway.

Then 2. internal communication doesn't matter either, because everything you are trying to do is inside a module.

In other words, it person_p

is exactly like a regular global variable in your module, and you can do whatever you want.

It is only a pointer that is defined by that line of code, so you can dynamically allocate memory elsewhere and assign a memory address person_p

if you like.

0


source







All Articles