Fix error in rebase
Fix some resource leaks in non used error paths (found via coverity)

replace malloc with calloc in some places and add null pointer checks
to try and debug segmentation faults.