繁体   English   中英

使用pthread在C ++中获取分段错误

[英]Getting a segmentation fault in c++ using pthreads

我正在为我的操作系统类编写一个带有线程的程序。 它必须在一个线程中计算n个斐波纳契数列的值,并将结果输出到主线程中。 当n> 10时,我一直遇到分段错误。通过测试,我发现正确执行了execute_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);
}
num = new int(atoi(argv[1]));

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

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

将第一行更改为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM