You're trying to pfree(target) after having altered the targetpointer inside the main loop of the function...
regards, tom lane