Move UE context creation and storage to after successful PDU encoding to prevent memory leaks if encoding fails. Also add proper PDU cleanup when AMF fetch fails and use consistent NULL check style. This ensures UE context is only stored when the operation is guaranteed to succeed, improving error handling and memory management.