Is it better to allocate memory in the power of two?

后端 未结 11 1047
执笔经年
执笔经年 2020-12-08 04:26

When we use malloc() to allocate memory, should we give the size which is in power of two? Or we just give the exact size that we need?
Like



        
11条回答
  •  长情又很酷
    2020-12-08 04:52

    You should use realloc() instead of malloc() when reallocating. http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/

    Always use a power of two? It depends on what your program is doing. If you need to reprocess your whole data structure when it grows to a power of two, yeah it makes sense. Otherwise, just allocate what you need and don't hog memory.

提交回复
热议问题