malloc(0)和free(NULL)

原创
2022/01/11 20:42
阅读数 124

先看man 3 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.

总结就是:

  1. malloc(0)和free(NULL)合法
  2. malloc的结果可以作为free的参数,但只能free一次
  3. malloc(0)可能返回非NULL指针,使用这个非NULL指针会有溢出问题
展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部