gpt4 book ai didi

c - 指向 pthread_create() 最后一个参数的指针导致崩溃

转载 作者:行者123 更新时间:2023-11-30 14:24:21 25 4
gpt4 key购买 nike

刚刚遇到一个关于如何将第四个参数传递给 pthread_create() 的奇怪问题。

原来我写的代码如下:

auditLogEntry *newEntry = NULL;

// malloc and init the memory for newEntry
rc = audit_init_log_entry(&newEntry);
// wrapper of 'goto cleanup'
ERR_IF( rc != 0 );
...
rc2 = pthread_attr_init(&attr);
ERR_IF( rc2 != 0 );
rc2 = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
ERR_IF( rc2 != 0 );
rc2 = pthread_create(&syslog_thread, &attr, syslog_thread_handler, (void *)newEntry);
ERR_IF( rc2 != 0 );
newEntry = NULL;
...
cleanup:
pthread_attr_destroy(&attr);
if (newEntry != NULL)
{
audit_free_log_entry(newEntry);
newEntry = NULL;
}

static void *syslog_thread_handler(void *t)
{
auditLogEntry *entry = (auditLogEntry *)t;
... // code using entry
cleanup:
audit_free_log_entry(entry);

pthread_exit(0);
}

一切正常。

然后,我做了如下更改:

rc2 = pthread_create(&syslog_thread, &attr, syslog_thread_handler, (void *)&newEntry);
ERR_IF( rc2 != 0 );
...
cleanup:
pthread_attr_destroy(&attr);
if (rc != 0 && newEntry != NULL)
{
audit_free_log_entry(newEntry);
newEntry = NULL;
}

static void *syslog_thread_handler(void *t)
{
auditLogEntry **entry = (auditLogEntry **)t;
... // code using *entry
cleanup:
audit_free_log_entry(*entry);
*entry = NULL;

pthread_exit(0);
}

在上述更改之后,线程处理程序将使用 *entry 来访问日志条目数据。但这没有用。更糟糕的是,进程核心被转储。

我尝试了“man pthread_create”,但发现没有特别提及如何将最后一个参数传递给它。

我在这里有什么错误的行为吗?

最佳答案

您没有显示完整的代码,因此很难判断发生了什么。

但是,&newEntry 为您提供了指向堆栈上变量的指针。如果 newEntry 超出范围,例如因为你的函数结束了,你的另一个线程现在有一个无效的指针 - 指向堆栈上现在已经消失的位置。取消引用这样的指针会导致未定义的行为。

int *foo(void) 
{
int x = 2;
return &x;
}

void bar(void)
{
int *x = foo();
printf("%d\n", *x); //can't do this, x points to something
//on the stack in the foo function,
//which isn't valid any more
}

如果 foo() 函数将 &x 传递给它创建的线程,您也会遇到同样的问题。

void foo(void) 
{
int x = 2;
...
pthread_create(&tid, bar, NULL, &x);
}

void *bar(void *arg) { int *x = arg;

   printf("%d\n", *x); //same problem here, x points to something
//on the stack in the foo function, which isn't valid
//if the foo function ends. This concept is exactly the same
//if x had been a pointer inside the foo() function.
}

这可能是您的场景:

int globalx = 2; //global variable
void foo(void)
{
int *x = malloc(sizeof(int));
...

pthread_create(&tid, bar, NULL, &x); //we're still taking the address of
//a local variable.
}

void *bar(void *arg)
{
int **x = arg;
printf("%p\n", *x); //still the same problem here, x points to something
//on the stack in the foo function, which isn't valid
}

关于c - 指向 pthread_create() 最后一个参数的指针导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11867591/

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