Segmentation fault (core dumped)

Feb 12, 2014 at 1:15am
Now I know that the error "Segmentation fault (core dumped)" means that I have a pointer in my code pointing to memory it isn't authorized to access. But the problem is I don't even have a pointer in the following program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cmath>
using namespace std;

int power3(int p, int q){
    if (q == 0) return 1;
    if (q == 1) return p;
    if (q%2 == 0) return p * power3((power3(p,(q/2))),2);
    else if (q%2 != 0) return p * power3((power3(p,((q-1)/2))),2);
}

int main(){
    int a, b;
    cin >> a;
    cin >> b;
    cout << power3(a, b);
    return 0;
}


I'm thinking the only thing that could be responsible is line 8 or 9, or both. I tried as much as I could to fix it. Does anyone have an idea of what to do?
Feb 12, 2014 at 1:21am
You probably have an infinite loop, and that's the cause.

After some time, you end up out of stack space, causing segfault.
Feb 12, 2014 at 1:40am
You have an infinite loop. Consider what happens when you encounter the following code:
power3((power3(p,(q/2))),2); // line 8

using the input: p = 5, q = 2
1
2
3
4
5
...
if (q % 2 == 0)
// inner function executes: power3(5, 1); and returns p
// outer function executes: power(5, 2)
// Uh oh looks like we are back to where we started 


I am not trying to show that your code produces an infinite loop with the given input, I'm instead trying to draw your attention to the constants you leave unhandled in your function calls
Feb 12, 2014 at 1:41am
Is there a problem with my translation of the mathematical formula to c++ code?

Its supposed to be this for line 8 (and I just realized I did this one wrong) : (pq/2)2

and this for line 9: p x (p(q - 1)/2)2
Feb 12, 2014 at 1:48am
Smac89, then shouldn't the function work fine if q is not 2, but is, for example, 3?
Feb 12, 2014 at 2:16am
The function will still not work if q is not 2. Let's take that example again with p = 5 and now q = 3

1
2
3
4
else if (q % 2  != 0)
// inner function executes with power3(5, (3 - 1)/2 = 1); and returns p
// outer function executes with power3(5, 2);
// infinite loop again 


Feb 13, 2014 at 8:38pm
I'm really sorry, I should've posted in the beginners forum. I just don't understand why the function loops over and over. I've been trying but I can't seem to think of anything that I can do. I understand how it loops if q = 2 || 3, but if q = 8 then shouldn't it be able to work?
Feb 13, 2014 at 9:16pm
You need `q==2' as a base case.

> I understand how it loops if q = 2 || 3,
> but if q = 8 then shouldn't it be able to work?
then you didn't understand.
for q \notin {0,1} you will call power3(_, 2)
Feb 13, 2014 at 10:28pm
Thanks I finally get it now, I'm so slow. But thank you!
Topic archived. No new replies allowed.