1. 程式人生 > 其它 >Leetcode 錯誤:store to misaligned address

Leetcode 錯誤:store to misaligned address

技術標籤:Programming Language

今天遇到了一個 leetcode報的錯:

Line 48: Char 21: runtime error: store to misaligned address 0x61400000009e for type 'char *', which requires 8 byte alignment [solution.c]
0x61400000009e: note: pointer points here
61 00 62 00 be be be be be be be be be be be be be be be be be be be be be be be be be be be be

^

對應的程式碼是:

void * alloc_buf(int size)
{
    void *tmp = g_buffer + g_idx;
    g_idx += size;
    return tmp;
}

應該是這個函式返回的地址沒有按照8位元組對齊。

修改如下:

void * alloc_buf(int size)
{
   size = (size + 0x7) & (~0x7);
    void *tmp = g_buffer + g_idx;
    g_idx += size;
    return tmp;
}

問題解決了