Fix dns use-after-free bug

Spotted with valgrind while developing the socks5 feature. See d931724c0's comment for bug analysis and 71e12f6d5's comment for a description of the fix.