Fixed c++ code to handle segmentation fault