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

后端 未结 2 906
离开以前
离开以前 2020-12-15 04:15

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

2条回答
  •  孤城傲影
    2020-12-15 04:38

    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.)

提交回复
热议问题