c - malloc和realloc的关系,当内存中没有所需的空间时如何处理

标签 c memory-management malloc realloc

Possible Duplicate:
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 字节,其中 2 字节用于声明 int 类型的指针,另外 6 字节由 malloc 函数占用,剩余 2 字节被其他程序占用,现在当我运行realloc函数来扩展指针指向的内存,它将在内存中搜索10个字节,当它不可用时,它会从堆区域分配10个字节的内存,并复制malloc的内容并将其粘贴到新分配的内存区域中堆区然后删除malloc中存储的内存对吗?

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

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

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

最佳答案

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.

关于c - malloc和realloc的关系,当内存中没有所需的空间时如何处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12122751/

相关文章:

C - 指针算术

c - 当您尝试在 c 中释放()已经释放的内存时会发生什么?

memory - 倒排页表如何处理多个进程访问同一帧

iPhone Objective-C 自动发布泄露

c - 为什么调用 `free(malloc(8))` ?

c - 是否有在 C 中分配内存的最佳实践?

c++ - 如何确定符号链接(symbolic link)指向的文件路径?

c - 在 C 中使用 malloc 初始化结构

c - 观察其他 C 程序正在运行的程序的事件。 [报告击键]

c - Malloc() 缓冲区太小