man malloc / man free
The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc(), or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.
不太確定malloc(0)的使用場景,尤其是返回值是implementation defined。blog 裏有標準的條款,也有glibc的實現和測試代碼,不錯!
free(NULL),記得之前都是會crash的…,man page說是safe的,好吧……不過對於同一段內存free的時候還是要注意,例如下面的代碼
char *p = malloc(10);
free(p);
p = NULL; //需要設置爲NULL,這樣以後同一段內存就不會被重複free了
free(p); // do nothing since p is NULL now.