For Programmers: Free Programming Magazines  


Home > Archive > Unix Programming > July 2007 > some error which should not be there









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author some error which should not be there
Ravi

2007-07-20, 7:10 pm

#include <stdio.h>
#include <pthread.h>
pthread_key_t pkt_fp;
void *thread_start(void *v)
{
FILE *fp;
char fname[30];
sprintf(fname,"x%p",pthread_self());
pthread_setspecific(pkt_fp,fp);
fp = fopen(fname,"w");
fprintf(fp,"This is the thread with ID %p",pthread_self());
fflush(fp);
return NULL;
}

void clean_up(void *v)
{
fclose((FILE *)v);
}

int main(void)
{
pthread_t tid1, tid2;
pthread_key_create(&pkt_fp,clean_up);
pthread_create(&tid1,NULL,&thread_start,NULL);
pthread_create(&tid2,NULL,&thread_start,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
}
I inspected the above code and it gives segmentation fault at fclose
in the function void clean_up(). Can you please help me know why this
is happening?

Rainer Weikusat

2007-07-20, 7:10 pm

Ravi <ra.ravi.rav@gmail.com> writes:
> #include <stdio.h>
> #include <pthread.h>
> pthread_key_t pkt_fp;
> void *thread_start(void *v)
> {
> FILE *fp;
> char fname[30];
> sprintf(fname,"x%p",pthread_self());
> pthread_setspecific(pkt_fp,fp);
> fp = fopen(fname,"w");
> fprintf(fp,"This is the thread with ID %p",pthread_self());
> fflush(fp);
> return NULL;
> }
>
> void clean_up(void *v)
> {
> fclose((FILE *)v);
> }
>
> int main(void)
> {
> pthread_t tid1, tid2;
> pthread_key_create(&pkt_fp,clean_up);
> pthread_create(&tid1,NULL,&thread_start,NULL);
> pthread_create(&tid2,NULL,&thread_start,NULL);
> pthread_join(tid1,NULL);
> pthread_join(tid2,NULL);
> }
> I inspected the above code and it gives segmentation fault at fclose
> in the function void clean_up(). Can you please help me know why this
> is happening?


By the time you set the key value, the value of 'fp' is
indeterminate, because it hasn't yet been set to a valid value.
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com