Differences between using realloc vs. free -> malloc functions

前端 未结 5 1009
自闭症患者
自闭症患者 2020-12-23 19:59

Why would one use realloc() function to resize an dynamically allocated array rather than using free() function before calling the malloc() function again (i.e. pros and con

5条回答
  •  鱼传尺愫
    2020-12-23 20:31

    I had a program that was doing a bunch of free() and malloc() calls to make a dynamic array, and I thought I'd optimize by reusing the existing array when possible. Benchmarks showed that realloc() on average is slower than just calling free() and malloc(). I guess it makes sense, since sometimes it would grow, and maybe require copy.

提交回复
热议问题