简体   繁体   中英

How to avoid Segmentation Fault

Here i have a code that translates numerical characters into roman literals, the following code works for little value smaller than 3 digits, it was supposed to work until 4 digits, when numbers are greater than 1000 it returns a segmentation fault exception. What are segmentation faults and how to avoid them

#include <unordered_map>
#include <iterator>
#include <iostream>
#include <vector>
using namespace std;
int quotient(int nominator, int denominator);
string solution(int number){
 std::unordered_map<int,string> Configuration;
 std::string result;
 int multimes=0;
 string character;
 Configuration[1000]="M";
 Configuration[500]="D";
 Configuration[100]="C";
 Configuration[50]="L";
 Configuration[10]="X";
 Configuration[5]="V";
 Configuration[1]="I";
 vector<int> NumConfig={1000,500,100,50,10,5,1};
 for(vector<int>::iterator it=NumConfig.begin();it!=NumConfig.end();++it)
 {
   multimes=quotient(number,*it); 
   number-=multimes* (*it);
   character=Configuration.find(*it)->second;
   int var=0;
   if(multimes>0 && multimes<=3 ){
   while(var < multimes)
   {
     result.append(character);
     var++;
   }}
   else if(multimes>3)
   {
     result.append(Configuration.find(*it-1)->second);
     result.append(character);
   }
 }
 return result;
}
int quotient (int nominator,int denominator)
{
    int result=(int)nominator/denominator;
    return result;
}
int fromint (istream &str){int x;str>>x;return x;}
int main()
{
    while(true)
    {
        cout<<solution(fromint(cin));
    }
    return 0;
}

try use debug tools such as assert, put it preceding any pointer assignment to guard it

// ...
for(vector<int>::iterator it=NumConfig.begin();it!=NumConfig.end();++it){
  assert( it != nullptr );

  // ...
}

if a pointer prepared in such guard is violated ie. the boolean result is false then:

assertion "it != nullptr" failed: file " ....

I could see the segmentation fault when input is equals to (5n -1) (ie 4,9,14...) , where n is any natural number. Configuration.find(*it - 1) returning Configuration.end()

avoid segmentation fault by explicit check for Configuration.end()

EDIT

*it-1 which is subtracting *it value by one instead pointing to previous value from Configuration . You can change it to *(it-1) to avoid fragmentation error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM