簡體   English   中英

使用C中的線程進行分段錯誤

[英]Segmentation fault using threads in C

我在這段代碼中遇到段錯誤,但在任何地方都找不到問題。 它可以使用-lpthread進行編譯,但是不會運行。 該程序從命令行獲取一個整數,然后創建一個新線程以使用該值計算collat​​z猜想。 這是我的代碼:

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

void print_con();
void calc_con(int *n);

int * values[1000];

int main(int argc, char * argv[])
{
        int* num;
        *num = 15;
        pthread_t thread;
        pthread_create(&thread,(pthread_attr_t*)NULL, (void *)&calc_con, (void *)num);
        pthread_join(thread, NULL);
        print_con();
        return 0;

}

void calc_con(int *n)
{
        int i = 0;
        int * x;
        *x = *n;
        *values[0] = *x;
        while(*x > 1)
        {
                if(*x % 2 == 0)
                        *x /= 2;
                else if(*x % 2 == 1)
                {
                        *x *= 3;
                        *x++;
                }
                i++;
                *values[i] = *x;
        }
        pthread_exit(0);
}

void print_con()
{
        int i;
        for(i = 0; i < 1000; i++)
        {
                if(*values[i] > 0)
                        printf("%d", *values[i]);
        }
}

好的,您需要void *作為參數傳遞給pthread_create ,但是您仍然需要尊重基本知識:

int* num;
*num = 15;
pthread_t thread;
pthread_create(&thread,(pthread_attr_t*)NULL, (void *)&calc_con, (void *)num);

這里*num = 15; 您正在將15寫入未初始化的指針 那是未定義的行為

我會做:

int num = 15;
pthread_t thread;
pthread_create(&thread,(pthread_attr_t*)NULL, &calc_con, &num);

請注意,您不必從非void的指針強制轉換為void * 由於num是在main例程中聲明的,因此您可以將指針安全地傳遞給線程。

請注意,正如dasblinkenlight指出的那樣,您還必須在calc_con修復接收端,它具有相同的問題:

int * x;  // uninitialized pointer
*x = *n;  // copy data "in the woods"

只需取消引用到局部變量,您就可以擁有自己的價值:

int x = *((int *)n);

還有一個:

int * values[1000];

是未初始化的整數指針數組,而不是您想要的整數數組。 它應該是

int values[1000];

然后

values[0] = x;

(並不是因為有很多*運算符才是好代碼)

您正在使用void*int傳遞給線程。 這將在許多平台上運行,但是不能保證該數字將正確“往返”。 返回指針后,將其保存在取消引用的未初始化指針中,這是不正確的。

將指針傳遞給num ,然后將指針直接復制到x

void calc_con(void *n);
...
void calc_con(void *n) {
        int i = 0;
        int * x = n;
        *values[0] = *x;
        while(*x > 1) {
                if(*x % 2 == 0) {
                        *x /= 2;
                } else if(*x % 2 == 1) {
                        *x *= 3;
                        *x++;
                }
                i++;
                *values[i] = *x;
        }
        pthread_exit(0);
}
...
int num = 15;
pthread_create(&thread,(pthread_attr_t*)NULL, calc_con, (void *)&num);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM