if this is a bad idea, how to allocate memory in the function?
It's not necessarily a bad idea to allocate memory in a function. You just have to be sure to clean it up appropriately.
The problem is that you might lose the ability to do that once you leave function scope.
Just be careful with your design. Match up malloc with free every time and you won't have memory leaks.