calloc 需分配 n * size 位元組並歸零。關鍵在於正確處理迴圈與歸零邏輯。
void *calloc(size_t n, size_t size) {
char *memory = (char *)malloc(n * size);
if (memory == NULL) return NULL;
char *ptr = memory;
while (n-- > 0) {
*ptr++ = '\0';
}
return memory;
}
注意: 原碼迴圈條件有誤,已修正為 n-- > 0 確保正確歸零所有位元組。
使用 realloc 動態擴展陣列,每讀入一個整數即擴充一個 int 大小。
#include
#include
int *readints() {
int *array = NULL;
int value;
int length = 0;
while (scanf("%d", &value) == 1) {
int *temp = (int *)realloc(array, (length + 1) * sizeof(int));
if (temp == NULL) {
free(array);
return NULL;
}
array = temp;
array[length++] = value;
}
return array; // 呼叫端負責 free
}
改進點: 原碼初始分配 1 個元素再擴充,改為從 0 開始更自然;新增 temp 變數防止 realloc 失敗導致記憶體洩漏。
逐字元讀取並動態擴展,結尾補 \0。使用 fgets 或 getchar 替代不安全的 gets。
#include
#include
char *readstring() {
char *array = NULL;
int ch;
int length = 0;
while ((ch = getchar()) != EOF && ch != '\n') {
char *temp = (char *)realloc(array, (length + 1) * sizeof(char));
if (temp == NULL) {
free(array);
return NULL;
}
array = temp;
array[length++] = (char)ch;
}
/* 追加結束符 */
char *temp = (char *)realloc(array, (length + 1) * sizeof(char));
if (temp == NULL) {
free(array);
return NULL;
}
array = temp;
array[length] = '\0';
return array;
}
關鍵修正: 原碼使用 gets(ptr) 且邏輯混亂,已重寫為安全、標準的逐字元讀取模式。
動態記憶體管理是 C 語言核心難點,掌握「分配→檢查→使用→釋放」完整生命週期,並養成「用暫存指標接 realloc」習慣,能避免絕大多數記憶體錯誤。