pthread_create 导致分段错误 [英] pthread_create causing segmentation fault

查看:16
本文介绍了pthread_create 导致分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序包含以下代码.

My program contains the following code.

pthread_t PThreadTable[32];

 for (i=1; i<P; i++) // Checked with P = 4 
    {
        long    i, Error;

        printf( "pthread_create %d!
", i );
        Error = pthread_create(&PThreadTable[i], NULL, 
          (void * (*)(void *))(SlaveStart), NULL);
        if (Error != 0) 
        {
            printf("Error in pthread_create().
");
            exit(-1);
        }
    }

 SlaveStart();

代码在调用 pthread_create 时出现分段错误(通过 gdbvalgrind 检查).为什么会这样?

The code gives segmentation fault on calling pthread_create (checked through gdb and valgrind). Why so?

推荐答案

因为你在循环中重新声明了变量i.循环内的变量正在被使用,它包含垃圾值.这就是为什么表达式 &PThreadTable[i] 指向一个错误的地址并且你得到一个分段错误.

Its because you redeclare variable i inside the loop. The variable inside the loop is being used and it contains garbage value. That is why, the expression &PThreadTable[i] points to a wrong address and you get a segmentation fault.

这篇关于pthread_create 导致分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆