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