1 #include
2 #include
3 #include
4 #include
5 #define PAI 3.14159
6 void* area(void* arg){
7 double r = (double)arg;
8 double* s=malloc(sizeof(double));
9 s = PAI * r * r;
10 return s;
11 }
12 int main(void) {
13 printf("r=");
14 double r;
15 scanf("%lf", &r);
16 pthread_t tid;
17 int error=pthread_create(&tid, NULL, area, &r);
18 if(error){
19 errno=error;
20 printf("%m\n");
21 }else {
22 printf("pthread_create success\n");
23 }
24 #if 0
25 double a;
26 pthread_join(tid, (void**)&a);
27 printf("s=%g\n", a);
28 free(a);
29 a=NULL;
30 #endif
31 #if 0
32 double* a = (double**)malloc(sizeof(double));
33 pthread_join(tid, (void**)a);
34 printf("s=%g\n", (double)a);
35 free(*a);
36 a=NULL;
37 free(a);
38 a=NULL;
39 #endif
40 #if 0
40 #if 0
41 double b=(double*)malloc(sizeof(double));
42 double** a=&b;
43 int error1=pthread_join(tid, (void**)a);
44 if(error1){
45 errno=error1;
46 printf("%m\n");
47 }
48 printf("s=%g\n", (double)a);
49 free(*a);
50 a=NULL;
51 free(b);
52 b=NULL;
53 #endif
54 #if 1
55 double* a;
56 int error1=pthread_join(tid, (void**)a);
57 if(error1){
58 errno=error1;
59 printf("%m\n");
60 }
61 printf("s=%g\n", (double)a);
62 free(*a);
63 *a=NULL;
64 #endif
65 return 0;
66 }
執行結果 :
r=4
pthread_create success
段錯誤 (核心已轉儲)
gdb跟蹤調試結果:
54 #if 1
55 double** a;
56 int error1=pthread_join(tid, (void**)a);
57 if(error1){
58 errno=error1;
59 printf("%m\n");
60 }
61 printf("s=%g\n", (double)a);
62 free(*a);
63 *a=NULL;
(gdb) l
64 #endif
65 return 0;
66 }
(gdb) b 54
Breakpoint 1 at 0x8048689: file ret.c, line 54.
(gdb) r
Starting program: /home/liushiwei/liushiwei/unix/14/a.out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/i386-linux-gnu/libthread_db.so.1".
r=3
[New Thread 0xb7dffb40 (LWP 7045)]
pthread_create success
[Thread 0xb7dffb40 (LWP 7045) exited]
Breakpoint 1, main () at ret.c:56
56 int error1=pthread_join(tid, (void**)a);
(gdb) p a
$1 = (double **) 0x8048709
(gdb) p *a
$2 = (double *) 0x18ebc381
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0xb7fb2e59 in pthread_join () from /lib/i386-linux-gnu/libpthread.so.0
(gdb) c
Continuing.
Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.
(gdb)
注意:前面三個#if 0 到#endif 都可以執行成功,但最後一個#if 1 到#endif,段錯誤,請大神幫幫小弟,已經糾結幾天了,不知道怎麼解決。謝謝!
一級指針也要捆綁存儲區呀