Page 93 - DCAP408_WEB_PROGRAMMING
P. 93
Unit 5: Memory Management (I)
As the space after the end of the block may be in use, realloc may find it essential to copy the Notes
block to a new address where more free space is obtainable. The value of realloc is the new
address of the block. If the block is required to be moved, realloc copies the old contents.
If you pass a null pointer for ptr, realloc behaves just like ‘malloc (newsize)’. This can be expedient,
but be cautious that older implementations (before ANSI C) may not sustain this behavior, and
will perhaps crash when realloc is passed a null pointer.
Similar to malloc, realloc may return a null pointer if no memory space is obtainable to make
the block bigger. When this occurs the original block is untouched; it has not been customized
or relocated.
In many cases it makes no distinction what happens to the original block when realloc fails,
since the application program cannot continue when it is out of memory, and the only thing to
do is to provide a fatal error message. Over and over again it is suitable to write and use a
subroutine, conventionally known as xrealloc, that takes care of the error message as xmalloc
does for malloc:
void *
xrealloc (void *ptr, size_t size)
{
register void *value = realloc (ptr, size);
if (value == 0)
fatal (“Virtual memory exhausted”);
return value;
}
You can also utilize realloc to make a block smaller. The reason you would do this is to evade
tying up a lot of memory space when only a little is required. Making a block smaller at times
necessitates copying it, so it can fail if no other space is obtainable.
Did u know? If the new size you state is the similar as the old size, realloc is assured to
modify nothing and return the similar address that you gave.
Self Assessment
Fill in the blanks:
8. The .................... function modifies the size of the block whose address is ptr to be newsize.
9. If you pass a null pointer for ptr, realloc behaves just like ‘.................... ‘.
10. Similar to malloc, realloc may return a .................... pointer if no memory space is obtainable
to make the block bigger.
5.5 Using LocalReAlloc()
The LocalReAlloc function modifies the size or the attributes of a stated local memory object.
The size can increase or decrease.
HLOCAL LocalReAlloc(
HLOCAL hMem, // handle of local memory object
LOVELY PROFESSIONAL UNIVERSITY 87