Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can realloc move pointer if new size smaller?

Tags:

c

realloc

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*ptr=(T*)malloc(n*sizeof(T));
//<--do something useful (that won't touch/reallocate ptr of course)
size_t n2=100;//or any value in [1,n-1]
T*ptr2=(T*)realloc(ptr,n2*sizeof(T));
//<-- are we guaranteed that ptr2==ptr ?

Basically, can the OS decide on its own that since we freed a large memory block, he wants to take advantage of all reallocs to defragment the memory, and somehow move ptr2 ?

like image 236
spirov Avatar asked Nov 15 '09 03:11

spirov


People also ask

Can you realloc to a smaller size?

The realloc function allocates a block of memory (which be can make it larger or smaller in size than the original) and copies the contents of the old block to the new block of memory, if necessary.

Does realloc change the pointer?

realloc() returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr, or NULL if the request fails.

Can realloc fail when shrinking?

realloc will not fails in shrinking the existing memory, so it will not return NULL .

Can I use realloc with new?

No! When realloc() has to copy the allocation, it uses a bitwise copy operation, which will tear many C++ objects to shreds. C++ objects should be allowed to copy themselves.


1 Answers

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".

like image 149
Alessandro Jacopson Avatar answered Sep 30 '22 05:09

Alessandro Jacopson