Avoid a couple of memory leaks and undefined behavior

Signed-off-by: Toon Schoenmakers <nighteyes1993@gmail.com>