Differences between using realloc vs. free -> malloc functions

前端 未结 5 1026
自闭症患者
自闭症患者 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:43

    Well, realloc may change the size of the block in place, or allocate a new one and copy as much as will fit. In contrast, malloc and free together can only allocate a new one, and you have to do your own copying.

    To be frank, realloc doesn't get as much use these days because it doesn't work well with C++. As a result, there's been a tendency for memory managers not to optimize for it.

提交回复
热议问题