malloc
- This will allocate the memory block if it is available, or else it will return NULL.
realloc
- If the size passed is greated than the existing block then this will tries to expand the existing memory, if it succeeds in expanding it will return the same pointer.
- Or else if its failed to exapand then it will allocate the new memory block and it will copy the old data from the old memory block to new memory block. Then it will free the old block and it will return the new blocks address.
- If allocating new memory block failed then it will simply return NULL, without freeing old memory block.
- If size passed is zero to the
realloc
function, then it will just free the old memory block and return NULL. realloc(ptr, 0)
is equivalent to free(ptr)
.
- If the size passed to the
realloc
function is lesser than the old memory block`s size, then it will shrink the memory.
Answer to your scenario
Listen to me: | 01 | 02 | 03 | 04 | 05 | 06 | 07 |08 |09 | 10 |
consider this as memory blocks: assume that 01 to 06 has been used by malloc()
func, 07 and 08 are free and last 2 blocks i,e 09 and 10 are being used by
memory of other programs. Now when i call realloc(p,10) i need 10 bytes but
there are only 2 free bytes, so what does realloc do? return a NULL pointer
or allocate memory form the heap area and copy the contents of 01 to 06
blocks of memory to that memory in the heap area, please let me know.
Yes it will copy content of 01
to 06
from old memory block to new memory block and it will free the old memory block and then it will return the address of new memory block.