Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abnormal Termination due to stack overflow

I recently wrote my Grad school Admission test few days back and the following question appeared in the test.
When the below function is invoked with any positive integer as argument, does it terminate? Also does it print anything?

void convert (int n) 
{
  if (n < 0)
    printf ("%d", n);
  else 
  {
    convert (n/2);
    printf ("%d", n%2);
  }
}

According to me, nothing will be printed as the control never reaches inside the if statement and also since the printf statement is placed after the function call under else block. The value of n never reaches below 0 and the function calls itself again and again till the stack overflows. My question is whether the code will abnormally terminate because of stack overflow?

like image 286
Beyond.Multiverse Avatar asked Feb 08 '19 16:02

Beyond.Multiverse


1 Answers

The code will not terminate with a positive integer argument since the base condition n < 0 will never be met.

The recursive call to convert calls it with the argument n / 2, which, as integer division, will inevitably reach zero, but never less than it.

For example, with the argument 10:

call convert(10)
10 < 0 is false; enter the else branch
call convert(10 / 2)
5 < 0 is false; enter the else branch
call convert(5 / 2)
2 < 0 is false; enter the else branch
call convert(2 / 2)
1 < 0 is false; enter the else branch
call convert(1 / 2)
0 < 0 is false; enter the else branch
call convert(0 / 2)
0 < 0 is false; enter the else branch
call convert(0 / 2)
0 < 0 is false; enter the else branch
call convert(0 / 2)
0 < 0 is false; enter the else branch

It will never enter the base case.

like image 172
Govind Parmar Avatar answered Oct 06 '22 00:10

Govind Parmar