Search code examples
c++clinuxwindowsstack-overflow

My program crashes on the Windows machine yet it works fine on the Linux


I tried to program Ackermann function on my notebook (Win10), however the program crashed at higher values instead of continuing to calculate for a few minutes or hours.

My friend tried the same code on his machine (SUSE) and it worked just fine, then we tried it on the school server (CentOS) and it crashed yet again.

EDIT: It worked on server too, it just needed a second try. It also worked on the other server we had tried... All of it is on Linux.

We suspect the stack overflow is behind it but it's weird, because values aren't THAT HIGH yet. How am I able to preform recursive functions on this system then?

Thanks for all the answers. I'm just curious why it happens and how to make it work on my machine.

I tried to use both C and C++ to no change.

#include <stdio.h>

int ackermann (int m, int n);

int main () {

  int m = 4;
  int n = 1;

  return ackermann(m,n);
}

int ackermann (int m, int n)
{
  if      (m == 0)          return n=n+1;
  else if (m > 0 && n == 0) return ackermann(m-1,1);
  else if (m > 0 && n > 0)  return ackermann(m-1,ackermann(m,n - 1));
}

Solution

  • In Visual Studio the default stack size is 1 MB, so with a recursion depth of 65535, and, I believe, a minimum stack frame for caller/function on x64 of this type is 72 bytes, so you will run out of available stack frame space for your program ( I compute almost 4.5Mb of stack needed for this scenario). This also produced the stack buffer overflow error, and has nothing to do with stack smashing other than you went beyond the maximum stack size available to your program when compiled.

    Most compilers including Visual Studio let you specify the stack size.

    More details: https://learn.microsoft.com/en-us/cpp/build/reference/f-set-stack-size?view=vs-2017

    [ Edited to reflect 65,535 frames, and not 1.4 billion ]