3

My default stack size (according to ulimit -s) is 8192 kB, so naturally the code below segfaults when I try to run it. Also, naturally, it works fine if I do a 'ulimit -s 9000'. However, when I do a 'ulimit -s unlimited' the code segfaults again. Any ideas what is going on here?

If it's useful, I'm running Debian 10 with kernel 4.19.0-6 and gcc version Debian 8.3.0-6.

#include <iostream>
#include <unistd.h>
#include <cstdlib>

void* wait_exit(void*)
{
  char bob[8193*1024];
  return 0;
}

int main()
{
  pthread_t t_exit;
  int ret;
  
  if((ret = pthread_create(&t_exit,NULL,wait_exit,NULL)) !=0)
  {
    std::cout<<"Cannot create exit thread: "<<ret<<std::endl;
  }
  std::cout<<"Made thread"<<std::endl;
  sleep(5);
  return 0;
}
user3856370
  • 237
  • 2
  • 8

1 Answers1

5

Because for threads "unlimited" gives you only 2 MiBs on x86_64, see pthread_create man page:

If the RLIMIT_STACK resource limit is set to "unlimited", a per-architecture value is used 
for the stack size.  Here is the value for a few architectures:

              ┌─────────────┬────────────────────┐
              │Architecture │ Default stack size │
              ├─────────────┼────────────────────┤
              │i386         │               2 MB │
              ├─────────────┼────────────────────┤
              │IA-64        │              32 MB │
              ├─────────────┼────────────────────┤
              │PowerPC      │               4 MB │
              ├─────────────┼────────────────────┤
              │S/390        │               2 MB │
              ├─────────────┼────────────────────┤
              │Sparc-32     │               2 MB │
              ├─────────────┼────────────────────┤
              │Sparc-64     │               4 MB │
              ├─────────────┼────────────────────┤
              │x86_64       │               2 MB │
              └─────────────┴────────────────────┘
Vojtech Trefny
  • 16,922
  • 6
  • 24
  • 48
  • 2
    Who'd have thought? That's not my idea of unlimited. Anyway nice and simple solution. Thanks. I guess the safer approach is to use pthread_attr_setstacksize. – user3856370 Nov 20 '20 at 17:51
  • 2
    Thank. It is always good to learn new meanings of words. Like all butter mince pies (have palm oil, or no brine olives have sea salt) – ctrl-alt-delor Nov 20 '20 at 18:19