During my experience with C coding, I’ve seen 2 ways of passing arguments for functions:
-
mallocbefore calling functions -
mallocinside functions (variable is not initialized before calling function)
I, particularly, prefer the second form. But while I’m the only one to code my program, I know that, but some else could not know, and could lead to 2 malloc, and leak of memory.
So, my question is: What’s the best practice for this?
Allocating memory in the caller is more flexible, because it allows the caller to use static or automatic storage instead of dynamic allocation, and eliminates the need to handle the case of allocation failure in the callee. On the other hand, having the caller provide the storage requires the caller to know the size in advance. If the size is compiled into the caller as a constant and the callee is in a library that’s later updated to use a larger structure, things will break horribly. You can avoid this, of course, by providing a second function (or external variable in the library) for retrieving the necessary size.
When in doubt, you can always make two functions:
Then the caller is free to choose whichever method is more appropriate for the particular usage case.