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

时间:2012-08-08 15:09:55

标签: c pthreads

刚刚遇到一个关于如何将第4个参数传递给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);
}

在上述更改之后,线程处理程序将使用*条目来访问日志条目数据。但它没有用。更糟糕的是,流程核心被抛弃了。

我试过'man pthread_create',但没有特别提到最后一个参数应该如何传递给它。

我的任何错误做法,在这里?

2 个答案:

答案 0 :(得分:2)

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

但是,&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 
}

答案 1 :(得分:0)

无论核心转储是什么,都不是来自pthreads。你在最后一个论点上所做的事情绝对没问题。