void *do_chld(void *arg)
{
char *sub;
sub = malloc(255 * sizeof(char));
/*
------ Some Code ----
*/
free(sub);
pthread_exit((void *)0);
}
上述函数传递给pthreads。当程序执行时,我得到了分段错误。一旦我评论对free(sub)
的呼叫,我的代码就可以正常工作。我无法弄清楚为什么?我们不能在线程中动态释放内存吗?由于堆在与主线程关联的所有对等线程中共享。通过pthred throws分段错误释放堆分配区域
编辑1-全码
void *do_chld(void *arg)
{
int new_fd = (int) arg;
int i,n,val;
char buf[255];
char *sub;
sub = malloc(255 * sizeof(char));
printf("Child thread [%d]: Socket number = %d\n", pthread_self(), new_fd);
/* read from the given socket */
n = read(new_fd,buf,100);
if(n<0){
fprintf(stderr,"Receieving Failed\n");
exit(2);
}
//process
printf("Received %s \n",buf);
val = checkSpelling(buf) ;
if(val){
sub = "Correct Spelling";
}
else{
sub = "InCorrect Spelling";
}
n = 0 ;
n = write(new_fd,sub,strlen(sub));
if(n<0){
fprintf(stderr,"Sending Failed\n");
exit(2);
}
/* close the socket and exit this thread*/
close(new_fd);
free(sub);
pthread_exit((void *)0);
}
我确定我没有访问/ * --- Some Code - * /中的堆。我张贴相同的参考。 – 2010-12-08 08:01:29