Home:ALL Converter>How to free memory allocated to local static pointer

How to free memory allocated to local static pointer

Ask Time:2014-05-08T17:31:27         Author:user3494614

Json Formatter

In legacy C code I have one pointer basically an array of size equal to one of enumerator and it is static in local scope. But now I have to remove that enumeration and now this static local array is giving error. I can convert that array to normal pointer and then allocate it dynamically but I am not sure how to do that. Below is sample code I have simplified from existing code base.

enum
{
E1,
E2,
EOL
};

void func
{
//static int array[EOL]; //-> that how it was earlier
static int *array = (int*)malloc(sizeof(int)*EOL); //Will this allocated memory only once
                                                   //or on every invokation.
free(array);//will it  free the memory more than once?
}

Now I can move array pointer to global scope and then allocate it in main and free it in atexit functions but I want to keep changes minimum as I am not sure of impact it will have in shared projects?

Thanks

Author:user3494614,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/23537890/how-to-free-memory-allocated-to-local-static-pointer
Vlad from Moscow :

If you want to keep changes minimal then simply move the enumeration definition inside the function body before this static variable. Or you can use even an unnamed enum with one enumerator for the size of the array.\n\nI do not understand your attempts to substitute the array for a dynamically allocated array.\n\nMoreover at present C allows to use variable length arrays. So your could define the function such a way that it had a parameter that would specify the size of the local (non-static) array.",
2014-05-08T09:51:32
user1983276 :

You can't initialise a static variable with something non const if you are using C.\n\nIf you are using C++, then the static pointer will only get a memory pointer allocated to it once.",
2014-05-08T13:14:43
mzero :

The malloc will occure only once.\n\n1) You can use a static boolean to let you know if the pointer in the array variable can be free.\n\n2) You can free the pointer then set it to NULL. The next occuration of the free will do nothing.",
2014-05-08T09:36:56
yy