Enhance memory safety: add null/zero-length checks and pointer resets, improve validation for memory mapping and cleanup on destruction