libc++abi.dylib: terminate called throwing an exception Abort trap: 6

15,927

In the line:

if (Number.at(i) != Number.at(M-i+1))

when i = 1 you try to access Number.at(M) which is out of the bounds of string M while M is the length of the string. Rather, it should be:

if (Number.at(i) != Number.at(M-i))
Share:
15,927
oxtay
Author by

oxtay

Okhtay is an EE engineer with a PhD degree, with experience in the areas of software-defined radios and cognitive radios. He has a new found passion in web app development and data sciences and is developing his skills in those areas. #SOreadytohelp

Updated on June 04, 2022

Comments

  • oxtay
    oxtay almost 2 years

    I am writing a code to find palindromic numbers. I am using this to also learn how to code and this is the code I have written:

    #include <iostream>
    #include <sstream>
    using namespace std;
    
    bool IsPalindromic (int n) {
        int I;
        string Number; //Starting to convert integer to string
        ostringstream convert;
        convert << n;
        Number = convert.str(); //Conversion is complete
        int M = Number.length();
        bool Result = true;
        if (M % 2 == 0)
            I = M / 2;
        else
            I = (M - 1)/2;
        for (int i = 1; i <= I; i++) {
            if (Number.at(i) != Number.at(M-i+1))
                Result = false;
        }
        return Result;
    }
    
    int main(int argc, char *argv[]) {
    int num;
    cout << "Enter an integer:";
        cin >> num;
        cout << IsPalindromic(num) << endl;
        return 0;
    }
    

    But when I try to run it and enter an integer as an input, I get the following error:

    libc++abi.dylib: terminate called throwing an exception 
    Abort trap: 6
    

    I can't find any error in logic of the code. Can you help me with identifying the problem? I am compiling using g++ on Mac OSX 10.8.4

  • oxtay
    oxtay almost 11 years
    So that means the characters in a string start at 0 and go to M-1. Thanks!
  • juanchopanza
    juanchopanza almost 11 years
    @user2613064 not only in strings. In arrays and all standard library containers.