Change source code to resolve problem with memory corruption and Segmentation fault