Cherry picked segfault fix from work branch (3baa22ffaa1d1ed478d082123d42f4a49abf73c1)