前陣子在 Hacker News Daily 上看到的,原文是 2016 的文章:「Why does calloc exist?」,裡面講的東西包括了 implementation dependent 的項目,所以要注意一下他的結論未必適用於所有的平台與情境。
malloc()
與 calloc()
的用法是這樣,其中 calloc()
會申請 count
個 size
的空間:
void* buffer1 = malloc(size); void* buffer2 = calloc(count, size);
第一個差異是,count * size
可能會 overflow (而 integer overflow 在 C 裡面是 undefined behavior),這點除非你在乘法時有檢查,不然大多數的行為都還是會生一個值出來。
而 calloc()
則是會幫你檢查,如果會發生 overflow 的時候就不會真的去要一塊記憶體用。
第二個差異是 calloc()
保證會將內容都設定為 0,這點在 POSIX 的標準裡面是這樣寫的:
The calloc() function shall allocate unused space for an array of nelem elements each of whose size in bytes is elsize. The space shall be initialized to all bits 0.
但作者就發現 malloc() + memset() + free()
還是比 calloc() + free()
慢很多:
~$ gcc calloc-1GiB-demo.c -o calloc-1GiB-demo ~$ ./calloc-1GiB-demo calloc+free 1 GiB: 3.44 ms malloc+memset+free 1 GiB: 365.00 ms
研究發現是 calloc()
用了 copy-on-write 的技巧,先把所有的 page 都指到同一塊完全被塞 0 的記憶體,只有在真的寫到該段記憶體時,系統才會要一塊空間來用:
Instead, it fakes it, using virtual memory: it takes a single 4 KiB page of memory that is already full of zeros (which it keeps around for just this purpose), and maps 1 GiB / 4 KiB = 262144 copy-on-write copies of it into our process's address space. So the first time we actually write to each of those 262144 pages, then at that point the kernel has to go and find a real page of RAM, write zeros to it, and then quickly swap it in place of the "virtual" page that was there before. But this happens lazily, on a page-by-page basis.
但畢竟這是 implementation dependent,看看有個印象就好。