2015-03-03 62 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; 
}