Fix potential crashes in optimization code (null pointer dereferencing)