# Why malloc() 不需要轉型 (cast) ###### tags: `C`, `malloc`, `explicit`, `cast` C99 2007 7.20.3 Memory management functions 提到: > The order and contiguity of storage allocated by successive calls to the **calloc**, **malloc**, and **realloc** functions is unspecified. **The pointer returned if the allocation succeeds ==is suitably aligned== so that ==it may be assigned to a pointer to any type of object== and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated)**. > > The **lifetime of an allocated object extends from the allocation until the deallocation.** Each such allocation shall yield a pointer to an object disjoint from any other object. > > **The pointer returned points to the start (lowest byte address) of the allocated space.** **If the space cannot be allocated, a null pointer is returned.** > > If the size of the space **requested is zero, the behavior is implementation-defined**: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object. * **C 語言 malloc 成功時是回傳開頭位址,並且會自動對齊,因此使用上根本不需要做轉型。** * [細看 malloc 關於 alignment 的實作](https://hackmd.io/@sysprog/c-memory?type=view#data-alignment) > 實際上到底 malloc 做了怎樣的 data alignment,繼續翻閱 The GNU C Library - Malloc Example,裡面特別提到: > > In the GNU system, the address is always a multiple of eight on most systems, and a multiple of 16 on 64-bit systems. > > **在大多數系統下,malloc 會以 8 bytes 進行對齊;而在 64-bit 的系統下,malloc 則會以 16 bytes 進行對齊。** > 對應的實驗,malloc 在 Linux x86_64 以 16 bytes 對齊: > > ```c > for (int i = 0; i < 10000; ++i) { > char *z; > z = malloc(sizeof(char)); > } > ``` > 結果用 gdb 測過之後,發現位址的結尾的確都是 0 結尾,表示真的是以 16-byte 做對齊。 * storage allocated 的生命週期是到 deallocation 為止,即 `free()` * 若 malloc 失敗會回傳 null pointer * malloc 一個 size = 0 的空間,此為未實作定義,不同編譯器有不同做法。