Is a malloc() needed before a realloc()?

♀尐吖头ヾ 提交于 2019-12-18 12:08:32

问题


Since I had read realloc will act as malloc if the size pointed is 0, I was using it without malloc(), provided the pointer was static, global, or explicitly set to NULL if automatic.

However, I notice a lot of programmers try to set it or set it to malloc(1). Is it needed?


回答1:


From Open Groups' specifications:

If ptr is a null pointer, realloc() shall be equivalent to malloc() for the specified size.

If ptr does not match a pointer returned earlier by calloc(), malloc(), or realloc() or if the space has previously been deallocated by a call to free() or realloc(), the behavior is undefined.




回答2:


malloc is not required, you can use realloc only.

malloc(n) is equivalent to realloc(NULL, n).

However, it is often clearer to use malloc instead of special semantics of realloc. It's not a matter of what works, but not confusing people reading the code.

(Edit: removed mention of realloc acting as free, since it's not standard C. See comments.)



来源:https://stackoverflow.com/questions/4459275/is-a-malloc-needed-before-a-realloc

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