Fix memory management and handling of null inputs.