首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Windows Native C 程式設計(九):動態記憶體、鏈結串列、位元欄位

     編輯:關於C語言

動態記憶體管理

核心函數

  • 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; // 防止野指標

常見錯誤

  • 配置太小卻寫入超量資料 → Heap corruption
  • free 後繼續使用 → Use-after-free
  • 將字串常值指標指給 malloc 回傳的指標 → 記憶體洩漏 + free 崩潰
  • 忘記 free → Memory leak

單向鏈結串列實作

typedef 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 位元組

位元欄位規則(MSVC 行為)

  1. 相鄰同型別位元欄位若總位元數 ≤ 型別大小,緊湊排列
  2. 超過型別大小則自動換到下一個儲存單元
  3. 不同型別相鄰:MSVC 不壓縮(各佔獨立單元),GCC 壓縮
  4. 穿插非位元欄位成員 → 後續位元欄位重新對齊
  5. : 0 強制換行;: n (無名稱) 為佔位用

記憶體區域速查

區域內容生命週期
Stack區域變數、函數參數函數返回自動釋放
Data/BSS全域/靜態變數程式結束釋放
Heapmalloc/new 配置手動 free/delete
RO Data字串常值、const 全域程式結束釋放

總結

  • 動態配置必須配對 free,並將指標設為 NULL
  • 鏈結串列靈活但有指標開銷,適合頻繁插刪、大小未知場景
  • 位元欄位用於極致省空間或硬體對應,注意編譯器差異與對齊規則
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved