realloc
is used to reallocate the memory dynamically.
Suppose I have allocated 7 bytes using the malloc
function and now I want to extend it to 30 bytes.
What will happen in the background if there is no sequential (continously in a single row) space of 30 bytes in the memory?
Is there any error or will memory be allocated in parts?
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:
realloc
works behind the scenes roughly like this:NULL
.So, you can test for failure by testing for
NULL
, but be aware that you don't overwrite the old pointer too early:FreeBSD and Mac OS X have the reallocf() function that will free the passed pointer when the requested memory cannot be allocated (see man realloc).
realloc
will only succeed if it can return a contiguous ("sequential" in your words) block of memory. If no such block exists, it will returnNULL
.From the man page:
So in other words, to detect failure, just check whether the result was NULL.
EDIT: As noted in the comment, if the call fails, the original memory isn't freed.