Problem
I get a stack overflow if I link against a library, and I don't get it if I don't. Here is the code:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define ASSERT_FATAL(cond) \
do { if (!(cond)) { printf("FAILED COND\n"); exit(-1); } } while(0)
void *func(void *dummy) {
// let's make sure the compiler doesn't optimize this out
volatile char buf[80000];
for (int i = 0; i < sizeof(buf); ++i)
buf[i] = rand() % 128;
sleep(1);
printf("Thread finished\n");
}
int main() {
pthread_t thread_id;
pthread_attr_t attr;
ASSERT_FATAL(pthread_attr_init(&attr) == 0);
ASSERT_FATAL(pthread_attr_setstacksize(&attr, 100000) == 0);
ASSERT_FATAL(pthread_create(&thread_id, &attr, func, NULL) == 0);
pthread_attr_destroy(&attr);
sleep(2);
return 0;
}
To reproduce:
- Runs fine with
gcc test.c -pthread -O3 - Crashes with stack overflow with
gcc test.c -pthread -O3 -Wl,--no-as-needed /usr/lib/x86_64-linux-gnu/libcholmod.so -Wl,--as-needed
NOTE: I use cholmod because that was the source of my problems in a larger codebase. In Ubuntu you can get it by installing libsuitesparse-dev.
My question
What's going on here? If I increase stack size it will work, but I want to understand what's causing it. Can the .so file do per-thread initialization and somehow reduce available stack space?
EDIT 1: changed all C++ code for pure C code
EDIT 2: assert result of thread creation/attribute setting