Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize static pointer with malloc in C?

I'm trying to initiate a static variable (inside a function) with malloc in C, but I'm getting the "initializer not constant error". I know that I can't initiate a static with non constants in C, but can anyone think of a solution? I need the code to have the same effect as this:

static int *p = (int *)malloc(sizeof(int));

Is there a trick/workaround?

EDIT: I have a function that is called every time a flag goes high. In this function, I'm creating and starting a new thread. I declare a pointer to a struct and use malloc to allocate memory then pass this pointer to the thread. Then the function returns control. When I re-enter the function, the thread that I opened initially will still be running and I want to be able to access the memory region that I originally passed to the thread. That's why I need a static so that I can malloc on the first call and then use the same address on subsequent calls. This way I can get info from the thread. All this to avoid using global variables.

like image 260
Arash Fotouhi Avatar asked May 23 '13 22:05

Arash Fotouhi


2 Answers

static int *p = NULL;
if(!p) p = (int *)malloc(sizeof(int));
like image 150
BLUEPIXY Avatar answered Oct 20 '22 12:10

BLUEPIXY


Assuming you want function-static variables:

int foo(void) {
    static int b=1;
    static int *p;
    if (b) {
        p =  malloc(sizeof(int));
        b = 0;
    }
    ...
}

You can use NULL value for p as a check, as long as you know it will never be NULL after the first call.

Remember to check for errors in malloc; it is a runtime allocation, and should also be freed when it will not be needed anymore.

like image 22
Elazar Avatar answered Oct 20 '22 12:10

Elazar