I don't understand why, in the following code snippet, the programmer used a static variable (and as a consequence I started to doubt all my little knowledge):
int func (...) {
static unsigned int *temp = NULL;
if( temp == NULL ) {
temp = malloc(dim*sizeof(*temp));
}
// do stuff with temp
}
In main(), func is called several time in a loop:
int main() {
for (i = 0; i < N; ++i)
x = func(...);
}
The first call to func initialise the variable temp to NULL and thus temp is allocated (maybe the initialisation is also redundant (according to this post).
The function func doesn't do anything special with temp, just copy some values to it from another (global) array if a condition is met and return the number of elements written.
If I understand correctly, malloc allocates the memory in the heap, thus the memory will be persistent until it is explicitly freed and as the pointer is static it can be accessed in subsequent calls.
Then the questions:
- Do I understand it correctly?
- Which is the advantage of this approach instead of malloc temp outside func and then explicitly pass it to func? I guess it depends on circumstances, ok, but maybe there is a well known example. I also saw this answer but I cannot understand the usefulness of the first example.
- I must free temp inside func (at the last step, which, by the way, is not done in this code)?
I need to modify the code above (which is a lot more complex) and I prefer to allocate temp outside func and then pass it to the function and I want to be sure that I am not missing something important. By the way I thought I could learn something :).
Thanks.