2015-03-03 61 views
1

我收到错误分割故障(核心转储)为什么分段错误存在的

我已经把范围做这些行功能的ThreadX

while (colatz_nums[j] != 1) 
     {j++; 
      if ((m % 2)==0) 
      { colatz_nums[j] = m/2;} 

      else 
      {colatz_nums[j] = 3 * m +1;} 
     } 

如果我删除这些行我不要错误。 我添加了一个测试while循环,它的工作原理 所以它必须是这些行中的东西。 请指出错误

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> // pid_t 
#include <unistd.h> 
#include <sys/ipc.h> 
#include <sys/shm.h> 
#include <sys/mman.h> 
#include <sys/fcntl.h> 
#include <sys/stat.h> 

#include <pthread.h> 

#define N 2 

void *thread (void *vargp); 
void *threadx(void *vargp); 

char **ptr; 

int fib_nums[25] ; 
int colatz_nums[25]; 
int last_collatz = 0; 

int main() 
{ 

    int i; 
    pthread_t tid[2]; 
    char *msgs[N] = { 
     "Hello from foo", 
     "Hello from bar" 
    }; 

    printf("Parent thread started with PID= %d and parent PID %d\n", getpid(), getppid()); 

    ptr = msgs; 

    pthread_create(&tid[0], NULL, thread, (void *)1); 
    printf(" 1st thread started with PID= %d and parent PID %d\n", getpid(), getppid()); 


    pthread_create(&tid[1], NULL, threadx, (void *)2); 
    printf("2nd thread started with PID= %d and parent PID %d\n", getpid(),  getppid()); 

    pthread_join(tid[1], NULL); 
    pthread_join(tid[0], NULL); 
} 

void *thread(void *vargp) 
{ 
    int myid = (int)vargp; 
    static int cnt = 0; 
    printf(" thread "); 

    int i=cnt; 
    for (;i <10 ;i=i+1) 
    { 
     printf("[%d] %d\n",myid, i); 
     sleep(cnt); 
    } 

    return NULL; 
} 

void *threadx(void *vargp) 
{ 
    int myid = (int)vargp; 
    static int cnt = 0; 
    printf(" threadx \n"); 
    int j = 0; 
    int m = 8; 
    colatz_nums[0] = 8; 

    while (colatz_nums[j] != 1) 
    { 
     j++; 
     if ((m % 2)==0) 
     { 
      colatz_nums[j] = m/2; 
     } 

     else 
     { 
      colatz_nums[j] = 3 * m +1; 
     } 
    } 
    last_collatz = j; 

    for (j=0; j <= last_collatz; j++) 
     printf (" j %d",colatz_nums[j]); 

    printf ("\n"); 
    return NULL; 
} 
+0

有你用调试器试过了吗?我的猜测是你要超出数组边界。 – Barmar 2015-03-03 02:10:21

+0

发生分段错误时'j'的值是多少? – Barmar 2015-03-03 02:10:57

回答

0

你永远不检查绑定的colatz_nums。您正在使用j和增量它访问它,而不将其限制在24

您先执行

colatz_nums[0] = 8

该数组的第一个值设置为8。然后你去将它与1比较它不是,然后循环,直到你在数组中找到1为止。

你的循环中的问题是,你通过增加j开始,然后将位于索引j(这是你将在下一回合中测试1的下一个值)的值设置为永远不会为1的值4或25,但在你的例子中总是4)。

然后,您将永久循环直到出现崩溃(出界限访问)。

0

m从未变化如此colatz_nums[j]不断被设置为4(因为m是八,偶数),权利,直到在那里你跑出阵列的结束点。

您可以通过简单地把这个线最后那个while循环内解决这个问题:

m = colatz_nums[j]; 

,或者重写为类似一个更安全的变种,避免未定义行为:

while (colatz_nums[j] != 1) { 
    j++; 
    if ((m % 2)==0) 
     m = m/2; 
    else 
     m = 3 * m + 1; 

    if (j == sizeof(colatz_nums)/sizeof(colatz_nums[0])) { 
     fprintf (stderr, "Buffer overflow\n"); 
     exit (1); // or some other method of stopping 
    } 
    colatz_nums[j] = m; 
}