malloc(size):配置 size 位元組,回傳 void*(未初始化)calloc(n, size):配置 n * size 位元組並歸零free(ptr):釋放 malloc/calloc 配置的記憶體char *p = malloc(100);
if (!p) { fprintf(stderr, "OOM\n"); exit(1); } // 必須檢查
strncpy(p, "hello", 100); // 安全複製
// ... 使用 p ...
free(p); // 釋放記憶體
p = NULL; // 防止野指標
free 後繼續使用 → Use-after-freemalloc 回傳的指標 → 記憶體洩漏 + free 崩潰free → Memory leaktypedef struct Employee {
int id;
char *name;
struct Employee *next; // 指標域
} Employee;
Employee *create_list(int n) {
Employee *head = NULL, *tail = NULL;
for (int i = 0; i < n; ++i) {
Employee *node = malloc(sizeof(Employee));
node->id = i;
node->name = "webabcd";
node->next = NULL;
if (!head) head = tail = node;
else { tail->next = node; tail = node; }
}
return head;
}
void free_list(Employee *head) {
while (head) {
Employee *tmp = head;
head = head->next;
free(tmp);
}
}
關鍵點:每個節點包含資料域與指向下一節點的指標域;尾節點 next = NULL;釋放時必須先保存 next 再 free 當前節點。
允許在結構體中指定成員佔用的位元數,節省空間或對應硬體暫存器佈局。
struct Flags {
unsigned int a : 1; // 1 bit
unsigned int b : 3; // 3 bits
unsigned int c : 7; // 7 bits
} f1; // 共用 4 位元組 (32 bits),緊湊排列
struct Gap {
unsigned int a : 1;
unsigned int : 0; // 強制對齊到下一個 int
unsigned int b : 3;
} f2; // 佔 8 位元組
struct Mixed {
unsigned int a : 1;
char ch; // 非位元欄位,打破壓縮
unsigned int b : 3;
} f3; // 佔 12 位元組
: 0 強制換行;: n (無名稱) 為佔位用| 區域 | 內容 | 生命週期 |
|---|---|---|
| Stack | 區域變數、函數參數 | 函數返回自動釋放 |
| Data/BSS | 全域/靜態變數 | 程式結束釋放 |
| Heap | malloc/new 配置 | 手動 free/delete |
| RO Data | 字串常值、const 全域 | 程式結束釋放 |
free,並將指標設為 NULL