Best practice for allocating memory for use by a function — malloc inside or outside?
c, malloc
Solution
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:
- The main function that uses caller-provided storage.
- A wrapper function which allocates the right amount of storage, calls the function in #1 using it, and returns the pointer to the caller.
Then the caller is free to choose whichever method is more appropriate for the particular usage case.
Problem
During my experience with C coding, I've seen 2 ways of passing arguments for functions: `malloc` before calling functions `malloc` inside 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?