Some bugfixes

Fixed errors in memory deallocation and returning values