简体   繁体   中英

Getting a segmentation fault in c++ using pthreads

I'm writing a program with threads for my Operating Systems class. It must compute n values of the Fibonacci series in one thread and output the results in the main thread. I keep getting a segmentation fault when n > 10. From my testing, I discovered that the compute_fibonacci function is executed correctly, but for some reason it never gets to the for loop in main. Here's the code with cout statements where the problem is. I appreciate any help on this.

#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]));

This is declaring a single int initialized with the integral value from argv[1] . Looks like you want to declare an array instead:

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

Change the first line to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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