Added checks for valid pointers after locking

if locking (due to memory full, etc) failed, it was crashing with invalid memory access before