Fix some mem allocation bugs