سؤال

I am trying to work through the Euler problems in C++ (as a learning tool) and I am up to question 4, how to find the largest palindromic product of two three digit integers. However, when I run my program I am given the error Segmentation fault (core dumped). I am not sure what I have done to cause this, could someone explain this to me?

Here is my code:

#include <iostream>
#include <string>

using namespace std;

bool palindrome(int x){
    string x_str = to_string(x);
    string x_str_rev = "";
    for(unsigned int i = x_str.length(); i > 0; i++){
        x_str_rev += x_str[i];
    };
    if(x_str == x_str_rev){
        return true;
    }
    else{
        return false;
    };
}

int main(){
    for(int i = 999; i > 100; i--){
        for(int x = 999; x > 100; x--){
            if(palindrome(i * x)){
                cout << i * x << endl;
                return 0;
            }
        };
    };
}
هل كانت مفيدة؟

المحلول

The criteria for your for loop in palindrome doesn't look right:

for(unsigned int i = x_str.length(); i > 0; i++){
    x_str_rev += x_str[i];
};

I expect that you meant to go through the string backwards right? What you're doing in the above code snippet is starting at the end of the string and going off into no-man's-land, which is going to cause undefined behaviour.

You should use a decrementing loop like this:

for(unsigned int i = x_str.length() - 1; i >= 0; --i){
    x_str_rev += x_str[i];
};

نصائح أخرى

for(unsigned int i = x_str.length(); i > 0; i++)

This is the problem line.

See what happens to the variable i when you execute this loop. Try running it step by step.

for(unsigned int i = x_str.length(); i > 0; i++){
    std::cerr << "i =" << i << std::endl;
    x_str_rev += x_str[i];
};

Learning to spot indexing issues is a big part of resolving segfault issues such as this.

Change

for (unsigned int i = x_str.length(); i > 0; i++){

to

for (unsigned int i = x_str.length()-1; i >= 0; --i){
                      ^^^^^^^^^^^^^^^^    ^^    ^^^

You have a loop that iterates over the chars in your string. But you increment i instead of decrementing:

for(unsigned int i = x_str.length(); i > 0; i++)

So this is

  1. an infinite loop
  2. Accesses an invalid index inside x_str. That's the reason for your segfault.

You have to start at length()-1 and use i-- instead to get it working.

In the future: Learn how to use a debugger. It will readily show you the line of code where a segmentation fault or similar is happening. And it's a skill you need to master anyway, if you're serious about programming.

For example, if your on Linux, you could have done the following:

gdb your-program
(gdb) run 
(gdb) bt

And it would have shown you where the segfault happens (if compiled with debugging symbols and without optimizations).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top