Stop leaks of memory and of privileges

Fix several memory leaks and mishandling of the privilege status
where a function returned failure indication, and previously
allocated memory was not freed (and the referece was lost), or
previously droped privileges where not restored.
use malloc() instead of alloca() and free after use