Malloc和Realloc关系,当内存中没有所需空间时,它如何处理

时间:2012-08-25 13:53:27

标签: c memory-management malloc realloc

  

可能重复:
  realloc and malloc functions

#include<stdio.h>
#include<stdlib.h>
void main()
{
  int *p;
  p = malloc(6);
  p = realloc(p, 10);
  if (p == NULL)
  {
    printf("error"); // when does p point to null consider i have enough space in prgrm
                     //memory area but not in memory where realloc is trying to search 
                     //for the memory, I dont know how to explain that try to undrstnd
   exit(1);
   }
}

以代码为例,假设总内存为10个字节,通过malloc函数指定类型为int和ohter 6字节的指针使用2个字节,其余2个字节被其他程序占用,现在当我运行realloc函数来扩展指针指向的内存,它将在内存中搜索10个字节,当它不可用时,它从堆区域分配10个字节的内存并复制malloc的内容并将其粘贴到新分配的内存区域中。堆区域然后删除存储在malloc中的内存吧?

realloc()是否返回NULL指针,因为内存不可用?没有权利!?它确实去堆区域进行内存分配吗?它没有返回NULL指针吗?

听我说: | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 |

将此视为内存块: 假设malloc()func使用01到06,07和08是空闲的,最后2个块i,e 09和10正被其他程序的内存使用。现在,当我调用realloc(p,10)时,我需要10个字节,但只有2个空闲字节,那么realloc的作用是什么?返回一个NULL指针或从堆区域分配内存,并将01到06块内存的内容复制到堆区域中的那个内存,请告诉我。

3 个答案:

答案 0 :(得分:2)

  

返回值

     

...

     

realloc()函数返回指向新分配的指针   记忆,适合任何类型的变量,可能是   与ptr不同,如果请求失败,则为NULL。如果大小相等   为0,NULL或适合传递给free()的指针是   回。如果realloc()失败,则原始块保持不变;它   没有被释放或移动。

答案 1 :(得分:2)

的malloc

  1. 这将分配内存块(如果可用),否则它将返回NULL。
  2. 的realloc

    1. 如果传递的大小比现有块大,那么这将尝试扩展现有内存,如果成功扩展它将返回相同的指针。
    2. 否则,如果它无法启动,那么它将分配新的内存块,并将旧数据从旧内存块复制到新内存块。然后它将释放旧块,它将返回新的块地址。
    3. 如果分配新的内存块失败,那么它将只返回NULL,而不释放旧的内存块。
    4. 如果传递的大小为零realloc函数,那么它将释放旧的内存块并返回NULL。 realloc(ptr, 0)相当于free(ptr)
    5. 如果传递给realloc函数的大小小于旧内存块的大小,则会缩小内存。
    6. 回答你的情景

      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.
      

      是的,它会将01的内容从旧内存块复制到06到新内存块,它将释放旧内存块,然后它将返回新内存块的地址。

答案 2 :(得分:0)

实现malloc的方式取决于系统或实现的定义。 (malloc的一个愚蠢但符合标准的实现总是会失败,返回NULL;大多数实际的实现都比这更好。)

首先阅读mallocreallocfree(Posix标准)的行为规范。

相关问题