malloc(0) actually works? [duplicate]

南笙酒味 提交于 2019-11-28 02:29:15

Why does malloc(0) actually return a valid pointer for writing?

It doesn't return a valid pointer for writing. It returns a valid pointer for not using it. Or it may return NULL as well since the C standard specifies this case to be implementation defined.

It is undefined behavior to dereference the pointer returned by malloc(0).

From the C Standard:

(C99, 7.20.3p1) "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."

malloc() is supposed to return a void* pointer. And it faithfully does that. But leads to UB when you dereference it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!