Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在c+中获得分段错误+;使用pthreads_C++_Pthreads_Segmentation Fault - Fatal编程技术网

C++ 在c+中获得分段错误+;使用pthreads

C++ 在c+中获得分段错误+;使用pthreads,c++,pthreads,segmentation-fault,C++,Pthreads,Segmentation Fault,我正在为我的操作系统类编写一个带有线程的程序。它必须在一个线程中计算斐波那契级数的n个值,并在主线程中输出结果。当n>10时,我总是遇到分段错误。从我的测试中,我发现compute_fibonacci函数执行正确,但由于某种原因,它从未到达主循环中的for循环。下面是问题所在的cout语句代码。我非常感谢你在这方面的帮助 #include <iostream> #include <pthread.h> #include <stdlib.h> #include

我正在为我的操作系统类编写一个带有线程的程序。它必须在一个线程中计算斐波那契级数的n个值,并在主线程中输出结果。当n>10时,我总是遇到分段错误。从我的测试中,我发现compute_fibonacci函数执行正确,但由于某种原因,它从未到达主循环中的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);
}
#包括
#包括
#包括
#包括
void*计算fibonacci(void*);
int*num;
使用名称空间std;
int main(int argc,char*argv[])
{
int i;
整数极限;
pthread_t pthread;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr,pthread_SCOPE_SYSTEM);
num=新的int(atoi(argv[1]);
限制=atoi(argv[1]);
pthread_create(&pthread,NULL,compute_fibonacci,(void*)limit);
pthread_join(pthread,NULL);
库特
这是在声明一个由
argv[1]
中的整数值初始化的
int
。看起来您想声明一个数组:

num = new int[ atoi(argv[1]) ];
这是在声明一个由
argv[1]
中的整数值初始化的
int
。看起来您想声明一个数组:

num = new int[ atoi(argv[1]) ];
将第一行更改为:

num = new int[atoi(argv[1])];
将第一行更改为:

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

好吧,我不敢相信我错过了。它现在运行良好。谢谢。好吧,我不敢相信我错过了。它现在运行良好。谢谢。