Fix potential memory leak due to realloc

If realloc returns NULL, the original memory is untouched, and if not
otherwise needed, must be freed manually.