Re: realloc shrink memory



On Sep 16, 11:07 pm, w...@xxxxxxxxxxx wrote:

Most realloc(void* ptr, size_t size) documents say that realloc
changes the size of ptr pointed memory block. But all the
following descriptions basically says the returned value is a
pointer to a new memory block.

Correct.

My question is that if realloc is called to shorten the allocated
memory, is it always hold that the return value is the same as the
argument ptr?

No. And there's no way you can even tell if you've asked to shorten
the allocated memory. For example, there's no reason an implementation
couldn't elect to round a requested size of 100 bytes up to an
allocated size of 128 bytes but a requested size of 90 bytes up to an
allocated size of 256 bytes. In this case, a request to change the
size to 90 bytes when it was previously requested as 100 bytes would
*not* be a request to shorten the allocated memory, only the
*guaranteed* allocated memory. (And I do in fact know 'realloc'
implementations that act this way based on heuristics.)

 Otherwise, the first sentence is misleading.

const size_t BSize=100;
void *p=malloc(BSize);
void *p1=realloc(p,BSize/2);
assert(p==p1);                // assured?

Not at all. For one thing, the smaller sized block may even come from
a completely different allocator.

DS
.



Relevant Pages

  • Memory leaks in server application
    ... Memory from multiple requests ... Each request is serviced independently inside a thread. ... memory inside single thread from its private heap. ... fully processed and all handles are closed and all allocated memory is ...
    (comp.unix.programmer)
  • Re: How to take in a string of any size?
    ... >the contents into the allocated memory. ... nobody said the string started at the beginning of the file. ... >number of calls to realloc() isn't going to be excessive). ...
    (comp.lang.c)
  • Re: Memory leaks in server application
    ... Memory from multiple requests ... Each request is serviced independently inside a thread. ... memory inside single thread from its private heap. ... fully processed and all handles are closed and all allocated memory is ...
    (comp.unix.programmer)
  • Re: Memory leaks in server application
    ... Memory from multiple requests ... Each request is serviced independently inside a thread. ... memory inside single thread from its private heap. ... fully processed and all handles are closed and all allocated memory is ...
    (comp.unix.programmer)
  • Re: Interprocess Communication & Performance
    ... For instance if the data items are small and ... memory the performance hit from the synchronization will overwhelm things. ... to map the allocated memory in both processes. ... memcpy's then using shared file mapping I think. ...
    (microsoft.public.win32.programmer.kernel)