我收到錯誤分割故障(核心轉儲)爲什麼分段錯誤存在的
我已經把範圍做這些行功能的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;
}
有你用調試器試過了嗎?我的猜測是你要超出數組邊界。 – Barmar 2015-03-03 02:10:21
發生分段錯誤時'j'的值是多少? – Barmar 2015-03-03 02:10:57