int a[200000]; // 危險!約 800 KB(假設 int 4 bytes)
區域陣列分配在堆疊,典型預設堆疊大小僅 1~8 MB(Windows 預設 1 MB,Linux pthread 常 8 MB)。800 KB 看似不大,但加上函式呼叫鏈、其他區域變數、編譯器對齊補齊,極易耗盡堆疊導致Stack Overflow,程式直接崩潰且無法捕獲。
#include <stdlib.h> // malloc, free
#include <stdio.h>
int main(void) {
size_t n = 200000;
int *a = malloc(n * sizeof *a); // 建議寫法:sizeof *a 自適應型別
if (!a) {
perror("malloc failed");
return 1;
}
// 使用 a[0] ~ a[n-1] 如同普通陣列
for (size_t i = 0; i < n; ++i) a[i] = (int)i;
free(a); // 用完必須釋放,避免記憶體洩漏
return 0;
}
free(a); a = NULL;。| 方案 | 適用場景 | 優缺點 |
|---|---|---|
static int a[200000];(靜態儲存期) | 全域/檔案域,生命週期=程式全程 | 不佔堆疊,但增加 BSS 段、不可釋放、執行緒不安全 |
int *a = calloc(n, sizeof *a); | 需零初始化 | 自動清零,稍慢於 malloc |
C99 變長陣列 (VLA) int a[n]; | n 為運行時常數且不大 | 仍分配在堆疊,不建議用於大陣列 |
C11 aligned_alloc / POSIX posix_memalign | 需特定記憶體對齊(SIMD、DMA) | 硬體友善,攜帶性稍差 |
C++ std::vector<int> a(n); | C++ 專案 | RAII 自動管理、擴容、邊界檢查 |
大陣列務必用動態記憶體。養成「malloc 檢查、用完 free、工具檢測」三步驟,是 C 程式穩健的基石。