Check malloc and realloc for memory errors.