簡體   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