lundi 2 mars 2015

Why is the segmentation Fault error occuring



I am getting error Segmentation fault (core dumped)


i have narrowed it done to these lines in function threadx



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

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


if I remove these lines I do not get the error. I added a test while loop and it worked So it must be something in these lines. Please point out the error



#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;


}




Aucun commentaire:

Enregistrer un commentaire