runtime error: member access within misaligned address(力扣最常見錯誤之一)
- 前言
- 原因和解決辦法
- 總結

前言
最近博主在刷力扣時,明明代碼邏輯都沒問題,但總是報下面這個錯誤:
runtime error: member access within misaligned address 0xbebebebebebebebe for type 'struct ListNode', which requires 8 byte alignment [ListNode.c]
0xbebebebebebebebe: note: pointer points here
原因和解決辦法
原因在于沒初始化,賦初值。
?
例如我們malloc下面這樣一個節點:
struct ListNode {int val;struct ListNode *next;};
struct ListNode* head;head=(struct ListNode*)malloc(sizeof(struct ListNode));
這樣對嗎?
由于LeetCode檢測機制更加嚴格,所以我們在創建節點是,還需將指針域賦值。
?
正確創建節點方式:
struct ListNode {int val;struct ListNode *next;};
struct ListNode* head;head=(struct ListNode*)malloc(sizeof(struct ListNode));head->next=NULL;
總結
- 問題:創建變量時,沒有初始化。
- 解決方法:創建變量后,立即置空或賦初值。
?
博主再多說一句,上述錯誤報告僅在LeetCode上出現,在牛客網上沒有。
由于兩個平臺測試機制不同,在此問題上沒有誰好誰壞。