modified the code not to overwrite memory