Shouldn't this be size + 1? Seems like you're writing past the end of the array below with r[i] = NULL