C-pthread分段错误11

C-pthread分段错误11,c,pointers,segmentation-fault,pthreads,C,Pointers,Segmentation Fault,Pthreads,我正在创建一个线程并向其传递一个指针。 但是当我将这个指针转换为应该返回的(int*)时,我有一个分段错误 int *ptr = (int *)ptrTotal2; int *ptr = (int *)ptrTotal2; *ptr = valA + valB; ... int *ptrTotal2 = 0; 代码如下: void *firstCalc(void *ptrTotal2){ int valA = 1; int valB = 2; int *ptr = (int *)

我正在创建一个线程并向其传递一个指针。 但是当我将这个指针转换为应该返回的(int*)时,我有一个分段错误

int *ptr = (int *)ptrTotal2;
int *ptr = (int *)ptrTotal2;
*ptr = valA + valB;
...
int *ptrTotal2 = 0;
代码如下:

void *firstCalc(void *ptrTotal2){
  int valA = 1;
  int valB = 2;
  int *ptr = (int *)ptrTotal2;
  *ptr = valA + valB;
  printf("Value of valA = %d\nValue of valB = %d\n", valA, valB);
  printf("Value of subtotal *ptrTotal1 = %d\n", *ptr);
  pthread_exit(NULL);
}

int main(int argc, char **argv) {

  pthread_t thread1;
  int *ptrTotal2 = 0;
  int iret1;

  iret1 = pthread_create(&thread1, NULL, firstCalc, (void*) ptrTotal2); 
  if(iret1){
    fprintf(stderr,"Error - pthread_create() return code: %d\n",iret1);
    exit(EXIT_FAILURE);
  }

  pthread_join( thread1, NULL);

  exit(EXIT_SUCCESS);

}

您需要取消引用
NULL
指针,这会导致分段错误,因为它是未定义的行为

试试这个

int value = 0;
int *ptrTotal2 = &value;

请保持
pthread_连接(thread1,NULL)
将被解除分配,并且再次出现未定义的行为。

当原始指针设置为0时,在函数
firstCalc
中取消引用
ptr
将导致未定义的行为,在您的情况下是分段错误

int *ptr = (int *)ptrTotal2;
int *ptr = (int *)ptrTotal2;
*ptr = valA + valB;
...
int *ptrTotal2 = 0;
而是为整数分配内存,并将其传递给创建的线程,并在线程结束后释放它:

int *ptrTotal2 = malloc( sizeof( int ) );
if( !ptrTotal2 )
{
    abort();
}

//... call pthread_create, pthread_join

free( ptrTotal2 );
注意,您必须使用分配的内存(使用malloc),因为从不同线程读取自动变量是实现定义的

6.2.4物品的储存期限

  • 试图从数据库间接访问具有自动存储持续时间的对象的结果 与对象关联的线程以外的线程是实现定义的

  • 分配指针时没有出现分段错误,之所以出现分段错误,是因为您在稍后尝试取消对指针的引用,该指针为NULL

    main()
    中,您已经编写了

     int *ptrTotal2 = 0;
    
    这基本上和

     int *ptrTotal2 = NULL;
    
    现在,在线程函数中,您正在执行

     *ptr = valA + valB;
    
    这是试图取消对空指针的引用。这引起了人们的注意。分割错误是UB的副作用之一

    你可以试着做的是

    • 使
      ptrTotal2
      成为
      int
      ,如
      int ptrTotal2=0
    • 传递它的地址,比如
      iret1=pthread\u create(&thread1,NULL,firstCalc,&ptrTotal2)

    您可以尝试
    printf
    指针的
    ptr
    值。它是一个
    NULL
    指针,因为
    ptrTotal2
    在那里也是一个
    NULL
    指针。然后在下面的表达式中

    *ptr = valA + valB;
    

    *ptr
    正试图从
    ptr
    指向的地址取消引用,不幸的是
    ptr
    指向空,因此发生了段故障

    嗯。这里出了什么错?谢谢,帮了大忙;)谢谢你的评论!