Fix realloc'ing freed/invalid pointers

See https://code.google.com/p/address-sanitizer/issues/detail?id=187 for the details