【问题标题】:segmentation fault during execution of program程序执行期间的分段错误
【发布时间】:2013-03-21 12:37:07
【问题描述】:

我写了一个程序来创建10个线程并正常运行它们。该程序运行良好,但最后它给出了分段错误。这是什么故障,是什么原因造成的,我该如何解决? 我的代码是:

#include<stdio.h>
#include<pthread.h>
void *print(void *num);

int main()
{
    pthread_t tid[10];
    int n,check;
    void *exitstatus;
    for(n=1;n<=10;n++)
    {
        check=pthread_create(&tid[n],NULL,print,(void *)&n);
        if(check=0)
            printf("thread created");
        pthread_join(tid[n],&exitstatus);
    }

    return 0;

} 

void *print(void *num)
{
    int i,*val=(int *)num;
    for(i=0;i<(5);i++)
        printf("Hello World!!!(thread %d )\n",*val);
}

【问题讨论】:

  • 你试过用gdb来隔离错误源吗?

标签: c linux gcc pthreads


【解决方案1】:

你有很多缺点:

for(n=1;n<=10;n++) // No, The array starts from 0 and lasts on 9

试试这个

for(n=0;n<10;n++)

if(check=0) // No, this will assign 0 to check instead of compare it

试试这个

if(check==0)

【讨论】:

  • 如果我们从 1 而不是 0 初始化 n,为什么会出现这个错误
  • @kanika 因为 C 和其他类似 C 语言的数组从 0 索引开始
【解决方案2】:

您正在访问超出其索引的数组。这是未定义的行为。

您的数组 t[10] 从索引 t[0] 开始,应该在 t[9] 结束 -

for(n = 0; n < 10; n++) { 
 //your stuff
}

check == 0 也是您检查相等性的方式。 check = 0 会将0 分配给check

所以你的代码必须是这样的:

#include<stdio.h>
#include<pthread.h>
void *print(void *num);

int main()
{
    pthread_t tid[10];
    int n,check;
    void *exitstatus;
    for(n = 0; n < 10; n++)
    {
        check=pthread_create(&tid[n], NULL, print, (void *)&n);
        if(check == 0)
            printf("thread created");
        pthread_join(tid[n], &exitstatus);
    }
    return 0;
} 

void *print(void *num)
{
    int i,*val=(int *)num;
    for(i = 0; i < 5; i++)
        printf("Hello World!!!(thread %d )\n", *val);
}

关于编程风格的另一个重要说明:请使用适当的缩进并明智地使用空格。如果使用适当的缩进和空格,大多数编程错误和错误都可以消除。例如,for 循环中运算符前后的一个空格,以及在, 之后和下一个参数之前调用函数时的参数之间。

【讨论】:

  • 一个澄清 - SEGFAULT(分段错误)意味着程序访问了对该程序无效的内存地址。这个访问数组末尾的程序就是一个很好的例子。请注意,C 这样不好。如果数组结束后还有有效内存,则使用&amp;tid[n] 会起作用,将结果写入其他一些可能有用的内存,从而产生垃圾。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-25
  • 2015-01-16
  • 2018-07-21
  • 1970-01-01
  • 1970-01-01
  • 2015-03-20
  • 1970-01-01
相关资源
最近更新 更多