首页 > 解决方案 > 添加链接依赖时堆栈溢出。链接减少了可用堆栈?

问题描述

问题

如果我链接到一个库,我会得到一个堆栈溢出,如果我不这样做,我就不会得到它。这是代码:

#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;
}

重现:

注意:我使用cholmod它是因为这是我在更大代码库中出现问题的根源。在 Ubuntu 中,您可以通过安装libsuitesparse-dev.

我的问题

这里发生了什么?如果我增加堆栈大小,它将起作用,但我想了解是什么原因造成的。.so 文件可以进行每个线程的初始化并以某种方式减少可用的堆栈空间吗?

编辑 1:将所有 C++ 代码更改为纯 C 代码

编辑 2:断言线程创建/属性设置的结果

标签: clinuxgccpthreads

解决方案


推荐阅读