use realloc to avoid memory leaks