免費開始練習
高考申論題 112年 [資訊處理] 程式設計

第 四 題

四、以下C++程式有部分違反安全程式設計原則,可能具有許多潛在風險。
01 #include
02 #include
03 #define SIZE 10
04 using namespace std;
05 class Food {
06 public:
07 Food() = default;
08 Food(int c) { cal = c; }
09 int getCal() { return cal; }
10 private:
11 int cal;
12 };
13 void f1() {
14 Food *f[SIZE];
15 cout<getCal()<16 }
17 void f2(int n) {
18 string *f = NULL;
19 for(int i = 0; i < n; i++)
20 f = new string("ok");
21 cout<<*f<22 }
23 void f3(int n) {
24 double x = 3, y1 = 5, y2 = 2;
25 for (int i=0; i26 x = x/10.0;
27 y1 = y1/10.0; y2 = y2/10.0;
28 }
29 if(x == (y1-y2)) cout<<"X == Y"<30 }
31 void f4(char *s1, char *s2) {
32 int len =0;
33 char *s =s1 ;
34 while (*s2!='\0') {
35 *s1=*s2;
36 s1++; s2++;
37 }
38 cout<39 }
40 void f5(int n) {
41 int result = 0;
42 int *d = new int[n];
43 d[0] = d[1] = 1;
44 for(int i = 0; i < n-2; i++) d[i+2] = d[i+1]+d[i];
45 for(int i = 0; i < n; i++) result = result + d[i];
46 cout<47 }
48 int main() {
49 char s1[]="goodness", s2[]="food";
50 f1();
51 f2(2);
52 f3(1);
53 f4(s1, s2);
54 f5(6);
55 return 0;
56 }
請說明此程式,執行函式f1()~f5()的輸出,以及函式f1()~f5()可能具有的潛在風險。(25分)
📝 此題為申論題

思路引導 VIP

看到本題,這是一個「安全程式設計」的經典考題。必須針對 f1 到 f5 五個函式,分別指出它們的「輸出結果」以及「潛在的安全風險/漏洞」。

  • f1():陣列 f 是指標陣列但未被初始化,f[0] 是一個野指標(Wild Pointer),提領它會導致崩潰。
🤖
AI 詳解 AI 專屬家教

【考點分析】 本題全面測驗 C/C++ 程式設計中常見的安全性漏洞與記憶體管理錯誤,包含:未初始化的指標(野指標)、記憶體洩漏(Memory Leak)、浮點數精度比較陷阱、以及緩衝區溢位(Buffer Overflow)。 【分析與論述】

▼ 還有更多解析內容

📝 同份考卷的其他題目

查看 112年[資訊處理] 程式設計 全題