iT邦幫忙

2025 iThome 鐵人賽

DAY 15
0

綜合前幾篇小結:

1.指標是位址,* 用來拿位址指到的值,& 取得位址

2.malloc 分配 heap,必須 free。用 sizeof *ptr 來寫 malloc 比較不易出錯

3.不要回傳指向區域變數的位址;回傳要 malloc 出來的記憶體或讓呼叫端傳 buffer

4.每個 malloc 都要有對應 free(或在程式結束前確認被釋放)

5.用 ASan / Valgrind 幫忙找到 subtle 的記憶體 bug

補充:偵錯工具與實務建議

  • 編譯旗標:-Wall -Wextra -std=c11 -g(早點看到 warning)
  • AddressSanitizer(快速檢查 use-after-free、越界)
    gcc -std=c11 -fsanitize=address -g your.c -o your && ./your
  • Valgrind(更完整的記憶體 leak 檢查):
    valgrind --leak-check=full ./your
  • 慣用風格:malloc(n * sizeof *ptr)、檢查 NULL、free(ptr); ptr = NULL;

上一篇
指標(pointer)與動態記憶體(malloc/calloc/realloc/free)常見錯誤
系列文
用leetcode系統化學習C語言15
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言