apply: fix memory leak.

If an invalid number of arguments was passed to a user defined
function, there was a chance for a memory leak. This patch
plugs the leak and adds a regression test to prevent the same
bug from coming up again.