-1

so Im trying to calculate a number raised to a power from user input, using scanf, but i keep on getting a segmentation fault.Does any one know why?This is my code:

int power( int base, int exponent){   
    int total=1;
    int temp = power(base, exponent/2);
    if (exponent == 0)
         return total;  // base case;

    if (exponent % 2 == 0)// if even
         total=  temp * temp;
         return total;
    if(exponent %2 !=0)// if odd
         total =(base * temp * temp);
         return total;
}

void get_info(){
    int base, exponent;
    printf("Enter a base number: ");
    scanf("%d", &base);
    printf("Enter an exponent: ");
    scanf("%d", &exponent);
    //call the power function
    printf("%d",power(base,exponent));

}

int main(){
    //call get_info
    get_info();
    return 0;
}

Any help would be much appreciated.Thank you.

chy4242
  • 11
  • 1
  • 1
    Visual studio had this little nugget to share: "warning C4717: 'power': recursive on all control paths, function will cause runtime **stack overflow**" (emphasis mine). And this was after I [took the seat belts off](https://stackoverflow.com/q/16883037/1460794) with `_CRT_SECURE_NO_WARNINGS`. – wally Dec 01 '17 at 13:23
  • 1
    @wally: I take the roof off too with the disabling of checked iterators. – Bathsheba Dec 01 '17 at 13:27
  • And beware of those ifs. You are writing C, not Python: you need to put braces around two statements. – marom Dec 01 '17 at 13:28
  • 1
    @Bathsheba Of course, we want speed right? – wally Dec 01 '17 at 13:30

1 Answers1

2

There's nothing to block the recursion in power:

int power( int base, int exponent){   
    int total=1;
    int temp = power(base, exponent/2); // round and round we go

The solution is to put

if (exponent == 0)
     return total;  // base case;

at the top of the function. C++ runtime libraries often issue a misleading termination message on a stack overflow such as this.

I'd also be tempted to use an else rather than testing the odd case explicitly. And fix the glaring issue with some missing { and }.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483