Fixed memory boundary issues and added exception handling