Search code examples
cmallocfreedynamic-memory-allocation

Do I "have to" free() static dynamically allocated pointers?


I have a function with a for loop and inside the loop (and depending on the input) certain variables are initialized once (the first time) using malloc().

These variables are declared like this:

static double *vector;

and then I allocate the memory using

malloc(size*sizeof(double));

The Question is:

Do I have to free these variables in the last iteration of the loop inside the called function or not?

UPDATE: maybe I explained myself wrong for some people. The thing is the called function (func_A) allocates memory for certain vectors it uses depending on the input from the main function. Then, this func_A is called several times from a loop in the main. That is why I define the variables as static, so that they are not defined everytime the func_A is called (for a matter of time consumption), because the dimensions will not change throughout the whole run. The variables are static but not global, so I can not free them from the main (right?).


Solution

  • You should always balance a malloc with a call to free.

    In your case, you could call it when you know you no longer need the vector.

    If that's not practical then you could always make a call to atexit; passing to it a pointer to a suitable function which will free the memory. See http://www.tutorialspoint.com/c_standard_library/c_function_atexit.htm

    Although you can often rely on operating systems to clean up for you on program termination, it's rather crude to rely on that.