Search code examples
c++recursionsegmentation-faultkaratsuba

terminated by signal SIGSEGV (Address boundary error) in recursive function


I'm trying to implement Karatsuba algorithm for multiplication. I'm kinda follow the pseudocode in this wiki page. But I'm always getting this error:

terminated by signal SIGSEGV (Address boundary error)

When I replaced the lines that cause the recursion to happen with something else:

z0 = multiply(a, c);
z1 = multiply(b, d);
z2 = multiply(a+b, c+d);

the error disappeared.

Here's my code:

#include <iostream>
#include <math.h>

long int multiply(int x, int y);
int get_length(int val);

int main()
{
  int x = 0, y = 0;
  long int result = 0;

  std::cout << "Enter x: ";
  std::cin >> x;
  std::cout << "Enter y: ";
  std::cin >> y;

  result = multiply(x, y);
  std::cout << "Result: " << result << std::endl;
  return 0;
}

long int multiply(int x, int y)
{
  if(x < 10 || y < 10) {
    return x * y;
  }

  int x_len = get_length(x);
  int y_len = get_length(y);

  long int z0 = 0 , z1 = 0, z2 = 0;
  int a = 0, b = 0, c = 0, d = 0;

  a = x / pow(10, x_len);
  b = x - (a * pow(10, x_len));
  c = y / pow(10, y_len);
  d = y - (c * pow(10, y_len));

  z0 = multiply(a, c);
  z1 = multiply(b, d);
  z2 = multiply(a+b, c+d);

  return (pow(10, x_len) * z0) + (pow(10, x_len/2) * (z2 - z1 - z0)) + z1;
}

int get_length(int val)
{
  int count = 0;
  while(val > 0) {
    count++;
    val /= 10;
  }
  return count;
}

Solution

  • I found the problem cause. It was because of these lines:

    a = x / pow(10, x_len);
    b = x - (a * pow(10, x_len));
    c = y / pow(10, y_len);
    d = y - (c * pow(10, y_len));
    

    It should be x_len / 2 instead of x_len and the same with y_len. Since it causes the recursion to be infinite.