- Do I understand this correctly?
You correctly understand temp initialization for all practical purposes and tasks, including that the explicit initializer is redundant. You also seem to understand the distribution correctly and mean temp declared by static . In practice, temp is probably initialized to NULL before func() ever called, and even if it is never called, but there is no way for the program to tell what the difference is from its initialization on the first call.
- What is the advantage of this approach instead of malloc temp outside func and then passing it func explicitly? I think it depends on the circumstances, well, but perhaps there is a well-known example. I also saw this answer, but I cannot understand the usefulness of the first example.
Presumably, the amount of storage required - as determined by the variable dim - is unknown until runtime. This is the reason for the dynamic distribution.
Placing a variable in the local area of ββthe function ensures that it has no connections - it is not visible and cannot be specified (directly) from anywhere outside the function. On the other hand, it is controlled by the function itself. Other functions need not worry about preparing an array for this function or passing one of them, and this function should not rely on anyone to properly configure the array.
As a stylistic question, I would be inclined to consider a static pointer to the file area (in the context of which, vaguely, the static means something else: internal communication, not static duration). The only difference would be the visibility of the variable.
Ultimately, however, the choice of visibility and the provision of a variable are design issues that have some solutions to some extent. You have not provided enough information for us to talk about specific options made in the code you are studying.
- Should I free temp inside func (in the last step, which, by the way, is not executed in this code)?
If temp freed, this should be done inside func() . One could set a copy of the temp pointer for code outside the function, in which case the allocated space could be freed using this pointer, but then temp would be left as an invalid pointer, without the possibility for func() to say.
However, the temp static creation point should certainly be stored in several function calls, so that the allocated space should not be freed and will not be skipped. Note, in particular, that since temp has a static duration, initialization to NULL is performed as if during program initialization, and not every time the function was called.
Actually, there is probably no need to free temp in this case. Doing this does not create a memory leak, because the memory allocated for temp still available unlimitedly (albeit within func() ). When the program exits, this memory will be returned to the operating system, like any other memory allocations still outstanding at that time.