程式輸入係數與指數後即「停止工作」,但 Debug 模式下卻能通過(常見未定義行為在 Release 下觸發)。
// 錯誤
L = (Linklist)malloc(sizeof(Linklist)); // Linklist 是指標型別,sizeof 只得指標大小 (4/8 byte)
P = (Lnode)malloc(sizeof(Lnode)); // Lnode 也是指標,同理
// 正確
L = (Linklist)malloc(sizeof(*L)); // 解參考取結構體大小
// 或
L = (Linklist)malloc(sizeof(struct { Lnode head; int length; }));
P = (Lnode)malloc(sizeof(struct lNode)); // 結構體標籤名
配置太小導致寫入 L->head、P->xi 時越界破壞堆元資料,釋放或下次配置時崩潰。
for (int i = 1; i <= m; i++) {
// ...
if (i == 1) { ... } break; // 第一次迴圈就 break,後續輸入全被跳過
for (int j = 2; j < i; j++) { ... }
// ...
break; // 外層迴圈也直接結束
}
應移除錯置的 break,改用正確插入邏輯(頭插/尾插/有序插入)。
typedef struct LNode {
int xi, zhi;
struct LNode *next;
} *Lnode, LNode;
typedef struct {
Lnode head;
int length;
} *Linklist, LinkList;
int InitList(Linklist L) {
L->head = (Lnode)malloc(sizeof(LNode)); // 頭結點
if (!L->head) return ERROR;
L->head->next = NULL;
L->length = 0;
return OK;
}
// 主程式插入邏輯 (尾插法示例)
Lnode rear = L->head;
for (int i = 1; i <= m; i++) {
int x, y; scanf("%d%d", &x, &y);
Lnode p = (Lnode)malloc(sizeof(LNode));
p->xi = x; p->zhi = y; p->next = NULL;
rear->next = p;
rear = p;
L->length++;
}
/RTC1 (Run-Time Checks) 或 AddressSanitizer (-fsanitize=address) 捕獲堆破壞。malloc 後檢查指標非 NULL。_CrtDumpMemoryLeaks() (MSVC) 檢測記憶體洩漏。核心教訓:malloc sizeof 要對結構體大小,不是指標大小;break 只用於明確跳出條件,別當縮排對齊工具。