What would realloc do if there is no sequential space of memory?

后端 未结 5 1603
一向
一向 2020-12-31 10:30

realloc is used to reallocate the memory dynamically.

Suppose I have allocated 7 bytes using the malloc function and now I want to extend i

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-31 10:52

    In general, it depends on the implementation. On x86(-64) Linux, I believe the standard doug lea malloc algorithm will always allocate a minimum of a standard x86 page (4096 bytes) so for the scenario you described above, it would just reset the boundaries to accomodate the extra bytes. When it comes to, say, reallocating a buffer of 7bytes to PAGE_SIZE+1 I believe it will try to allocate the next contiguous page if available.

    Worth reading the following, if you're developing on Linux:

    By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available. This is a really bad bug. In case it turns out that the system is out of memory, one or more processes will be killed by the infamous OOM killer. In case Linux is employed under circumstances where it would be less desirable to suddenly lose some randomly picked processes, and moreover the kernel version is sufficiently recent, one can switch off this overcommitting behavior using a command like:

    # echo 2 > /proc/sys/vm/overcommit_memory
    

    See also the kernel Documentation directory, files vm/overcommit-accounting and sysctl/vm.txt.

提交回复
热议问题