【问题标题】:Getting a segmentation fault in c++ using pthreads使用 pthread 在 C++ 中获取分段错误
【发布时间】:2011-12-14 13:53:29
【问题描述】:

我正在为我的操作系统类编写一个带有线程的程序。它必须在一个线程中计算斐波那契数列的 n 个值,并在主线程中输出结果。当 n > 10 时,我不断收到分段错误。从我的测试中,我发现 compute_fibonacci 函数正确执行,但由于某种原因,它永远不会进入 main 中的 for 循环。这是问题所在的带有 cout 语句的代码。感谢您对此提供的任何帮助。

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

void *compute_fibonacci( void * );

int *num;

using namespace std;

int main( int argc, char *argv[] )
{
    int i;
    int limit;
    pthread_t pthread;
    pthread_attr_t attr;

    pthread_attr_init( &attr );
    pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM );

    num = new int(atoi(argv[1]));
    limit = atoi(argv[1]);

    pthread_create(&pthread, NULL, compute_fibonacci, (void *) limit);
    pthread_join(pthread, NULL);

    cout << "This line is not executed" << endl;

    for (i = 0; i < limit; i++) {
        cout << num[i] << endl;
    }

    return 0;
}

void *compute_fibonacci( void * limit)
{
    int i;

    for (i = 0; i < (int)limit; i++) {
        if (i == 0) {
            num[0] = 0;
        }

        else if (i == 1) {
            num[1] = 1;
        }

        else {
            num[i] = num[i - 1] + num[i - 2];
        }
    }

    cout << "This line is executed" << endl;

    pthread_exit(0);
}

【问题讨论】:

    标签: c++ pthreads segmentation-fault


    【解决方案1】:
    num = new int(atoi(argv[1]));
    

    这是声明一个使用来自argv[1] 的整数值初始化的int。看起来你想声明一个数组:

    num = new int[ atoi(argv[1]) ];
    

    【讨论】:

    • 好吧,我不敢相信我错过了。现在运行良好。谢谢。
    【解决方案2】:
    num = new int(atoi(argv[1]));
    limit = atoi(argv[1]);
    

    将第一行改为:

    num = new int[atoi(argv[1])];
    

    【讨论】:

      猜你喜欢
      • 2011-10-26
      • 2016-04-22
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      相关资源
      最近更新 更多