<style>
.markdown-body code,
code {
color: #99999 !important;
background-color: #ffe9e5;
tab-size: 4;
}
</style>
# 安全程式設計<br> assignment#1
110590004 林奕廷
---
## 報告項目
+ FLP34-C <br> [Ensure that floating-point conversions are within range of the new type](https://wiki.sei.cmu.edu/confluence/display/c/FLP34-C.+Ensure+that+floating-point+conversions+are+within+range+of+the+new+type)
+ FLP36-C <br> [Preserve precision when converting integral values to floating-point type](https://wiki.sei.cmu.edu/confluence/display/c/FLP36-C.+Preserve+precision+when+converting+integral+values+to+floating-point+type)
---
## C語言的型態轉換
顯性轉換與隱性轉換
----
```c=
int A = 1;
float B = 2.0f;
double D = 4.0;
A = B; // 隱性轉換, A = 2
A = int(D); // 顯性轉換, A = 4
A = sizeof(1 ? 1 : 0.9) // 隱性轉換, A = 8 (double)
```
----
三個基本隱性轉型規則
+ 佔記憶體小 –> 佔記憶體大
+ 整數 -> 浮點數
+ 有號數 -> 無號數
---
### FLP34-C
Ensure that floating-point conversions are within range of the new type
----
```c=
// limits.h
#define INT_MIN (-2147483647 - 1)
#define INT_MAX 2147483647
// float.h
#define DBL_MAX 1.7976931348623158e+308
#define DBL_MIN 2.2250738585072014e-308
#define FLT_MAX 3.402823466e+38F
#define FLT_MIN 1.175494351e-38F
```
```c=
sizeof(int) // 4 byte
sizeof(float) // 4 byte
sizeof(double) // 8 byte
```
----
```c=
float x = 1e5F; // 10^5
float y = 1e20F; // 10^20
double z = 1e300; // 10^300
int num_i; // range: -2*10^9 ~ 2*10^9
float num_f; // range: ±1*10^-38 ~ 3*10^38
num_i = x; // good! in int range num_i = 10000
num_i = y; // bad! not in int range num_i = ???
num_f = z; // bad! not in float range num_f = ???
```
----
how to resolve this?
----
```c=
#include <limits.h>
#include <float.h>
#include <math.h>
int x;
float y = ...;
if (isgreater(fabsf(y), INT_MAX))
// handle undefined behavior
else
x = y;
```
----
```c=
#include <limits.h>
#include <float.h>
#include <math.h>
float y;
double z = ... ;
if (isgreater(fabs(z), FLT_MAX) ||
(z != 0.0 && isless(fabs(z), FLT_MIN) ))
// handle error
else
y = z;
```
---
### FLP36-C
Preserve precision when converting integral values to floating-point type
將整數轉換為浮點數時保持精度
----
浮點數精度:
IEEE754 標準下浮點數精度
float: 2^23 = 8388608
double:2^52 = 4503599627370496
```c=
int a = 1 << 10; // 2^10 = 1024
long long int b = 1LL << 40; // 2^40
int c = 1 << 24; // 2^24
long long int d = 1LL << 60; // 2^60
float num_f;
double num_d;
num_f = a; // 2^10 < 2^23 good!
num_f = b; // 2^40 > 2^23 bad!
num_d = c; // 2^24 < 2^52 good!
num_d = d; // 2^60 > 2^52 bad!
```
----
How to resolve this?
----
```c=
#incldue <stdlib.h>
int x = ...;
float y;
if (abs(x) > (1 << 23))
// handle error
else
y = x;
```
----
```c=
#incldue <stdlib.h>
long long int x = ...;
double y;
if (llabs(x) > (1 << 52))
// handle error
else
y = x;
```
---
## 結論
+ 顯隱性轉型功能
+ 潛在問題
+ 謹慎處理
---
## 報告結束
{"metaMigratedAt":"2023-06-18T05:00:16.294Z","metaMigratedFrom":"Content","title":"安全程式設計<br> assignment#1","breaks":true,"contributors":"[{\"id\":\"1c3e21e6-099a-4c9b-a39c-db2ab513a092\",\"add\":6103,\"del\":3082}]"}