if this is a bad idea, how to allocate memory in the function?
This question is easiest to answer if we reverse it:
malloc
'd in a function is also free
d in that same function?The answer is, there will be no memory leaks or dangling pointers, and this valuable outcome is achieved without cooperation of any other function. As a result, it is easier to get the code right, and the function has a simple interface.
Now, what if a function calls malloc
but not free
? Then there have to be rules about who is obligated to free the memory, when this is permitted to be done, and when it is required to be done. These rules become part of the function's interface, and anybody calling the function must either ensure that the rules or followed, or possibly impose similar rules on its caller(s), and so on. Explicit memory management adds complexity to interfaces, and the more complex the interfaces, the easier it is to make a mistake that leads to a memory error—and in C, a memory error can make your program crash.
Unfortunately, sometimes it is necessary to have an object that (a) must be allocated at run time and (b) must outlive the activation of the function that allocates it. In such cases, even though it seems like it might be a bad idea, we have no choice but to do the allocation, complicate the interface, and require the caller to manage the object correctly.
(One of the simpler cases is when an object is allocated at run time but is permitted to live forever. But you must bound the number of such objects or you'll run out of space.)