user3504101
user3504101

Reputation: 11

Threads passing arguments

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>

pthread_t id1,id2;
struct arg{int a[2];}*p;

void *sum(void *args)
{
    struct arg *b=((struct arg*)args);
    printf("hello:%d%d",b->a[0],b->a[1]);
}

void *mul(void *args)
{
    struct arg *c=((struct arg*)args);
    printf("hi:%d%d",c->a[0],c->a[1]);
}

main()
{
    int err1,err2;
    p->a[0]=2;
    p->a[1]=3;
    err1=pthread_create(&id1,NULL,&sum,(void*)p);
    err2=pthread_create(&id2,NULL,&mul,(void*)p);sleep(5);
}

I am trying to pass data to threads using structure .....but i always gets a segmentation fault error....can anyone tell me what's wrong with my code..

Upvotes: 1

Views: 76

Answers (2)

alireza_fn
alireza_fn

Reputation: 944

You are getting segmentation fault because you have not allocated memory for p; it tries to assign values to memory address 0 which leads to a segfault.

Try allocating memory with malloc:

main()
{
int err1,err2;
struct arg *p=(struct arg *)malloc(sizeof(struct arg));
p->a[0]=2;
p->a[1]=3;
err1=pthread_create(&id1,NULL,&sum,(void*)p);
err2=pthread_create(&id2,NULL,&mul,(void*)p);sleep(5);
}

Upvotes: 2

Cory Nelson
Cory Nelson

Reputation: 29981

You're getting a segfault because p is initialized to 0. You aren't assigning anything to it.

Upvotes: 1

Related Questions