Tidy up memory handling in the function so that it doesn't leak in odd conditions. Closes: bgo#635703