2013-03-21 68 views
1

我写了一个程序来创建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); 
} 
+0

您是否尝试过使用gdb来隔离错误的来源? – ziu 2013-03-21 12:41:57

回答

8

你有很多缺点:

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) 
+0

如果我们初始化n从1而不是0 – user3032010 2013-03-21 12:49:23

+0

@kanika,为什么会出现这个错误,因为C和其他C语言中的数组从0开始索引 – 2013-03-21 12:52:11

3

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

您的阵列t[10]开始在指数t[0],并应在t[9]结束 -

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

而且check == 0是你如何检查平等。 check = 0将分配给0check

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

#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循环中的运算符之前和之后的一个空白区域,以及在,之后和下一个参数之前调用函数时的参数之间的一个空白区域。

+0

一个说明 - SEGFAULT(段错误)是指程序访问的内存地址是该程序无效。这个程序访问数组的末尾是一个很好的例子。请注意,C这种方式很糟糕。如果在数组结束后有有效的内存,那么使用'&tid [n]'就会起作用,将结果写在其他可能有用的内存上,从而产生垃圾。 – ash 2013-08-25 05:14:09