fixed the realloc bug, made some changes to prevent bugs