【问题标题】:Segmentation Fault on strtol with in pthread function使用 pthread 函数的 strtol 上的分段错误
【发布时间】:2013-04-08 01:17:40
【问题描述】:

我在 pthread 内的以下代码块上收到“Segmentation Fault 11”:

void *func(void *len){
    char *temp = len;
    size = (int) strtol(temp, (char **)NULL, 10); // this throws the segfault
}

pthread create的写法如下:

int main(int argc, const char *argv[]){
    pthread_t t0;
    const char * length = argv[1];

    pthread_create(&t0, NULL, &func, (void *)length);
    // rest of code
    ...
}

让我感到困惑的是,SegFault 在编译并在终端中运行时被抛出,而不是在 Xcode 中。知道为什么会抛出它吗?

【问题讨论】:

  • 你是否也在从其他线程调用函数 func ?
  • 在将length 传递给pthread_create() 之后,您如何使用它? size 是什么?
  • 在将temp 传递给strtol() 之前,您测试tempNULL 的不同之处。您也可以使用argc 来测试argv[1] 是否包含任何有效的引用。

标签: c xcode terminal segmentation-fault pthreads


【解决方案1】:

除非您等待线程,否则main() 可能会在func() 甚至执行之前退出(因此argv 然后无效,因为它超出了那里的范围)。我的猜测是,这是在调试器中运行时消除的竞争条件,这就是为什么“在 Xcode”中运行它的原因(重要的不是 IDE,而是进程正在调试的事实)会有所帮助。

【讨论】:

  • 我稍后在代码部分的其余部分使用 pthread_join 来等待。对不起,我应该包括这个。那应该可以防止您所说的问题对吗?
  • @wbcrimson 是的,应该这样。然后代码中还有其他错误。
猜你喜欢
  • 1970-01-01
  • 2016-11-05
  • 2012-09-07
  • 2023-03-31
  • 1970-01-01
  • 2020-04-23
  • 1970-01-01
  • 2011-10-26
相关资源
最近更新 更多