This depends on context. In most hosted systems, using internal variables with static storage duration, or returning pointers to them, is frowned upon. Because that makes the functions unsuitable for multi-threading - they are not thread-safe unless you explicitly add mutex or similar mechanisms. And writing the function re-entrant, with caller allocation and no global resources etc is considered best practice when possible.
And of course, if the function doesn't reset the static storage resource, it can only be called once. This makes sense for a "singleton" design pattern, but not for a general library.
In freestanding (embedded etc) systems however, you often work with static memory pools, since such systems are often single-thread and also ban the use of heap allocation.
Generally, code using malloc is properly written if the code module that did the malloc
is also the one responsible for cleaning up its own mess, by providing a function for that, which is a wrapper around all necessary free()
calls. For every malloc call there should be a corresponding free call, in the same code. This goes for all manner of other dynamic resource too, file handles, threads etc.
The past ~40 years of C programming history shows that memory leaks most often appear when you come up with dysfunctional library APIs (like for example POSIX getline
), where the caller is made responsible to manually clean up something allocated by the library. If the library instead uses proper design with private encapsulation, memory leaks shouldn't happen.
Now of course C doesn't have RAII or destructors, so instead C programmers using a library must be trusted to activate their brain and call a function foo_cleanup()
if the "foo library" provides that one and tells the programmer to call it when they are done using the resource.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…