void *do_chld(void *arg)
{
char *sub;
sub = malloc(255 * sizeof(char));
/*
------ Some Code ----
*/
free(sub);
pthread_exit((void *)0);
}
위 함수는 pthreads로 전달됩니다. 프로그램이 실행되면 세그먼트 오류가 발생합니다. free(sub)
로 전화를 걸면 코드가 정상적으로 작동합니다. 나는 이유를 알아낼 수 없다? 스레드에서 메모리를 동적으로 해제 할 수 있습니까? 힙은 주 스레드와 관련된 모든 피어 스레드간에 공유되므로 당신이 /* -- Some Code -- */
없이 프로그램을 실행 시도 -pthred가 실행 한 함수로 힙 할당 영역을 해제하면 세그먼트 화 오류가 throw됩니다.
편집 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);
}
나는/* --- 일부 코드 - */내에서 힙에 액세스하지 않을 것이라고 확신합니다. 참조 용으로 게시하고 있습니다. –
@Eternal - 대신에'sub'의 값이 변경 될 수도 있습니다 - 자세한 내용은 최신 게시물을 참조하십시오. – Justin