[問題] 請問浮點數的運算(SIGFPE)

看板C_and_CPP (C/C++)作者 (施抄)時間15年前 (2011/04/05 13:15), 編輯推噓2(2010)
留言12則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) GCC 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) #include <signal.h> #include <float.h> 問題(Question): 想請問如何透過浮點數運算產生 SIGFPE 的 signal 餵入的資料(Input): 無 純測試 預期的正確結果(Expected Output): ./a.out SIGFPE 錯誤結果(Wrong Output): ./a.out min_normal = 2.22507e-308 min_normal = 1.7116e-309 max_normal = 1.79769e+308 max_normal = inf 程式碼(Code):(請善用置底文網頁, 記得排版) 程式很短 我直接貼在這裡 #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <float.h> void sig_fpe(int signo){ printf("SIGFPE\n"); exit(0); } int main(){ double x; signal(SIGFPE, sig_fpe); x = DBL_MIN; printf("min_normal = %g\n", x); x = x/13.0; printf("min_normal = %g\n", x); x = DBL_MAX; printf("max_normal = %g\n", x); x = x*x; printf("max_normal = %g\n", x); return 0; } 補充說明(Supplement): 我想要利用浮點數運算產生 SIGFPE 所以程式裡面故意產生 underflow 與 overflow 甚至還試過 division by 0 但是程式好像什麼事都沒發生一樣 可以正常結束 想請問一下要如何產生 SIGFPE 並且被 handler 偵測到 謝謝 我的 compile option 是 gcc -ftrapv -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.30.46

04/05 15:19, , 1F
用 raise(SIGFPE) 可以產生 signal, 標準並無規定實作
04/05 15:19, 1F

04/05 15:20, , 2F
品在浮點數運算錯誤時一定要發出 signal, -ftrapv 看
04/05 15:20, 2F

04/05 15:20, , 3F
起來好像沒效果似的 @@"
04/05 15:20, 3F

04/05 15:27, , 4F
An implementation need not generate any of these signa
04/05 15:27, 4F

04/05 15:28, , 5F
these signals, except as a result of explicit call to
04/05 15:28, 5F

04/05 15:28, , 6F
to the raise function. 就是跟 love 大說的那樣
04/05 15:28, 6F

04/05 15:29, , 7F
以前聽說 C 要做例外處理,要用 __try __except (微軟)
04/05 15:29, 7F

04/05 15:30, , 8F
非微軟系統就不清楚了。但是C++自己有 try catch 就是了
04/05 15:30, 8F

04/05 15:54, , 9F
Linux Kernel 對 EH 的做法是用 goto 去 free,fclose...等
04/05 15:54, 9F

04/05 15:55, , 10F
CRT (C Runtime) 原始碼用 __try 底層是用 SEH 機制
04/05 15:55, 10F

04/05 15:55, , 11F
看來用 C 的 signal 做例外處理,無論如何都是行不通
04/05 15:55, 11F

04/11 18:03, , 12F
數值作業
04/11 18:03, 12F
文章代碼(AID): #1DcgLgZr (C_and_CPP)
文章代碼(AID): #1DcgLgZr (C_and_CPP)