Malloc and Realloc relation, How does it handle when the required space is not available in memory [duplicate]

北慕城南 提交于 2019-12-02 08:27:28

RETURN VALUE

...

The realloc() function 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. If size was equal to 0, either NULL or a pointer suitable to be passed to free() is returned. If realloc() fails the original block is left untouched; it is not freed or moved.

malloc

  1. This will allocate the memory block if it is available, or else it will return NULL.

realloc

  1. 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.
  2. 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.
  3. If allocating new memory block failed then it will simply return NULL, without freeing old memory block.
  4. 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).
  5. 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.

The way malloc is implemented is by definition system or implementation dependent. (A silly, but standard conforming, implementation of malloc would always fail by returning NULL; most real implementations are better than this).

Read first the behavioral specifications of malloc, realloc, free (Posix standard).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!