Fixes for undefined behaviour on shutdown