0
votes

I am writing a program for multiplying big numbers using a karatsuba algorithm. There is a recursive function. Right before the recursive call I print string values and they are ok. Then, inside this function at the beginning I print the passed arguments again (I should get exactly the same results as before recursive call, earlier printf()) and I get segmentation fault.

This happen not on first function execution, but after many recursive calls.

My code:

void karatsuba(char *result, char *first, char *second)
{
    printf(" %s    %s\n", first, second);
    <somewhere here conditional return to end recursion>
    ...
    ...
    printf(" %s    %s\n", temp_first, temp_second);
    karatsuba(temp, temp_first, temp_second);
    ...
    ...
}

What do can cause segmentation fault in that case?

UPDATE:

Thank you all for your answers. Stack overflow is propably the reason. I created a static counter incremented at the start of recursive function and decremented at each of function ends and printed it. At the segmentation fault its value indicated depth of 46778.

Then, I increased stack size as Graham Borland pointed to 32MB. Now, counter indicated depth of 159126 calls, so increasing stack size made it better.

Sum of data in this function is 140B. Multiplying this value by stack depth gives me 21MB, which is less than 32MB.

After all, this number of recursive calls is too big. Doing calculation on paper I go maximum into <10 recursive calls for my data. Propably infinite recursion. :(

2
Make sure you don't get a stack overflow. - timrau
you have to come to the right place with your question - Stack Overflow !! - Arjun Sreedharan
Another reason that may cause segmentation fault is if the pointers don't actually point to somewhere meaningful. - Shahbaz

2 Answers

2
votes

You are likely to be busting the stack. Depending on the platform, you may be able to increase the stack available to your process. For example, on a Unix-like platform, entering this at the bash prompt before running your program:

ulimit -s 32768

will increase the stack to 32MB.

1
votes

The most probable reason is:
Stack Overflow

Infinite recursion??