If do the next:
int* array = malloc(10 * sizeof(int));
and them I use realloc:
array = realloc(array, 5 * sizeof(int));
On the second line (and only it), can it return NULL?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, it can. There are no implementation guarantees on
realloc(), and it can return a different pointer even when shrinking.For example, if a particular implementation uses different pools for different object sizes,
realloc()may actually allocate a new block in the pool for smaller objects and free the block in the pool for larger objects. Thus, if the pool for smaller objects is full, it will fail and returnNULL.Or it may simply decide it’s better to move the block
I just used the following program to get size of actually allocated memory with glibc:
and for n <= 6, it allocates 32 bytes, and for 7-10 it is 48.
So, if it shrank
int[10]toint[5], the allocated size would shrink from 48 to 32, effectively giving 16 free bytes. Since (as it just has been noted) it won’t allocate anything less than 32 bytes, those 16 bytes are lost.If it moved the block elsewhere, the whole 48 bytes will be freed, and something could actually be put in there. Of course, that’s just a science-fiction story and not a real implementation ;).
The most relevant quote from the C99 standard (7.20.3.4 The
reallocfunction):‘May’ is the key-word here. It doesn’t mention any specific circumstances when that can happen, so you can’t rely on any of them, even if they sound obvious at a first glance.
By the way, I think you could consider
realloc()somewhat deprecated. If you’d take a look at C++, the newer memory allocation interfaces (new/deleteand allocators) don’t even support such a thing. They always expect you to allocate a new block. But that’s just a loose comment.