gpt4 book ai didi

c - 使用 pthreads 和 malloc

转载 作者:行者123 更新时间:2023-12-04 02:56:48 25 4
gpt4 key购买 nike

我问了一个问题Using sockets in multithread server昨天。在这个问题中,我描述了多线程服务器中 Solaris 下的段错误。现在我已经找到了错误的核心并编写了代码,它很快就演示了它:

#include <stdlib.h>
#include <pthread.h>


int main(int argc, char *argv[])
{
pthread_attr_t *attr;

attr = (pthread_attr_t *)malloc(sizeof(pthread_attr_t));
pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED);

malloc(0);
malloc(0); //Segmentation fault there

return 0;
}

第二个 malloc 因段错误而崩溃。虽然此代码正常执行:

#include <stdlib.h>
#include <pthread.h>


int main(int argc, char *argv[])
{
pthread_attr_t *attr;

attr = (pthread_attr_t *)malloc(sizeof(pthread_attr_t));
// pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED);

malloc(0);
malloc(0);

return 0;
}

能否请您解释一下错误的原因?

P.S.:我使用 gcc -pthreads -lpthread -D_REENTRANT 键进行编译。

最佳答案

来自docs on pthread_attr_setdetachstate() :

The behavior is undefined if the value specified by the attr argument to pthread_attr_getdetachstate() or pthread_attr_setdetachstate() does not refer to an initialized thread attributes object.

attr 参数指向的 pthread_attr_t 对象可能包含指向由 pthreads 库维护的某些状态的指针。如果尚未初始化,该指针将是垃圾,因此 pthread_attr_setdetachstate() 调用可能会损坏堆。

参见 pthread_attr_init()函数以查看如何正确初始化属性对象。

关于c - 使用 pthreads 和 malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16523204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com