can realloc move pointer if new size smaller?

后端 未结 6 546
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 20:43

I am wondering whether the C or C++ standard guarantees that a pointer is not changed when realloc is called with a smaller (nonzero) size:

size_t n=1000;
T*         


        
相关标签:
6条回答
  • 2020-12-09 20:52

    With realloc, you get absolutely no guarantees about where the memory will live afterwords. I believe that libc's default malloc will only begrudgingly copy memory around, so practically speaking you may be OK. But don't count on it.

    0 讨论(0)
  • 2020-12-09 21:00

    There's no guarantee realloc will return the same location, period.

    0 讨论(0)
  • 2020-12-09 21:02

    realloc is not required to leave the block in place even if it would fit, and in fact the simplest stub implementation is an example where it might not:

    • malloc: call sbrk.
    • realloc: call malloc and memcpy.
    • free: no-op.

    This may sound ridiculous, but sometimes for embedded systems an implementation like I've just described is actually the optimal one.

    0 讨论(0)
  • 2020-12-09 21:08

    On Windows, the C-Runtime grabs a heap, and then allocates memory from that heap. So the OS won't know about individual memory allocations, and thus won't move things around.

    0 讨论(0)
  • 2020-12-09 21:09

    http://opengroup.org/onlinepubs/007908775/xsh/realloc.html

    Upon successful completion with a size not equal to 0, realloc() returns a pointer to the (possibly moved) allocated space.

    Nope, no guarantee

    0 讨论(0)
  • 2020-12-09 21:09

    It seems to me that all the current answers (at the time of this answer) do not refer to any standard document.

    For C++ I will refer to Working Draft, Standard for Programming Language C++, Document Number: N3337, Date: 2012-01-16, Revises: N3291 that, according to https://isocpp.org/std/the-standard, is the closest free document to the non-free official C++11 standard document; here we find at 20.6.13 C library:

    2 The contents are the same as the Standard C library header , with the following changes:[in my opinion the listed changes are not relevant to the question].

    So now we have to refer to the C standard.

    According to https://stackoverflow.com/a/83763/15485 the closest free document to the non-free official C11 standard document is Programming languages — C, N1570 Committee Draft — April 12, 2011 ISO/IEC 9899:201x; here we find at 7.22.3.5 The realloc function:

    4 The realloc function returns a pointer to the new object (which may have the same value as a pointer to the old object), or a null pointer if the new object could not be allocated.

    I am not a native English speaker and so is up to you to interpret the meaning of "may have".

    0 讨论(0)
提交回复
热议问题