Fix bug and increase allocation safety