0

Hello when I run this program for calculating the gcd through valgrind (this is the portion that is causing errors):

int gcd( int a, int b ) {

if( a == 0 || b == 0 )
  return a + b;
if( a < b )
  return gcd(b - a, a);
else
  return gcd(a - b, b);
}
int main(int argc, char **argv) {
int a = atoi( argv[1] );
int b = atoi( argv[2] );

int q = gcd(a, b);

fprintf(stdout, "%d\n", q);

return 0;
}

With no arguments I get

==22833== Invalid read of size 1
==22833==    at 0x3685636EB2: ____strtol_l_internal (in /lib64/libc-2.12.so)

and when I run it using two negative numbers ex: 'gcd -5 -4' I get

==516== Stack overflow in thread 1: can't grow stack to 0x7fe601ff8

I believe the second errors (with the negative number inputs) is because of the a < b part is this true? What part in the code is causing error 1 on its own?

user3295674
  • 893
  • 5
  • 19
  • 42

2 Answers2

1

No arguments
You are calling atoi() on an undefined variable.
First, you should check

if(argc != 3){ //check if there are three arguments
    //error code
}

Stack overflow
with a=-5 and b=4, a < b always. This causes an infinite recursion, and eventually a stack overflow.

EyeOfTheHawks
  • 576
  • 1
  • 5
  • 16
0

When one of the inputs to gcd is a negative number and other one is a positive number, the recursion never ends. The positive number keeps growing and the negative number remains unchanged in each successive recursive call. Obviously, this causes stack overflow.

When you pass two negative numbers to gcd, the next recursive call gets you in that state too.

R Sahu
  • 204,454
  • 14
  • 159
  • 270