realloc的()和malloc函数 [英] realloc and malloc functions

查看:156
本文介绍了realloc的()和malloc函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看那code:

#include<stdio.h>


 #include<stdlib.h>
void main()
{
  int *p;
  p = malloc(6);
  p = realloc(p, 10);
  if (p == NULL)
  {
    printf("error");
   exit(1);
   }
}

拿这个例子为code,假定总内存为10字节,两个字节用于指针的声明由malloc函数剩下的2个字节被其他程序占用为int类型和ohter 6个字节,现在当我运行realloc函数来扩展该指针所指向的内存,它会搜索10个字节的内存,当它不存在,它分配从堆区10个字节的内存和malloc的副本内容并粘贴到新的分配在堆区内存区域,然后删除存储在正确的malloc内存?

Take this example for the code, suppose the total memory is 10 bytes and 2 bytes is used by the declaration of pointer to type int and ohter 6 bytes by malloc function the remaining 2 bytes is occupied by other programs, now when i run realloc function to extend the memory that pointer is pointing to, it will search for 10 bytes in memory and when it is not available it allocates 10 bytes of memory from heap area and copies contents of malloc and paste it in new allocated memory area in heap area and then delete the memory stored in malloc right?

是否realloc()的返回NULL指针,因为内存不可用?无权利!?
它不会去堆区域的内存分配吧?它不返回NULL指针吧?

Does realloc() return a NULL pointer because the memory is not available? No right!? It does go to heap area for the memory allocation right? It does not return a NULL pointer right?

推荐答案

正确 - 如果的realloc 无法调整该内存块传递的,它使一个新的之一,复制数据,并释放旧的。

Correct -- if realloc can't resize the memory block you pass in, it makes a new one, copies the data, and deallocates the old one.

但是:


  1. 的malloc 的实施通常不会在一个字节的间隔运行。大多数的人我见过一轮的一切到最近的16个字节,因为它使会计更容易,许多用户将需要调整反正。在你的情况,这将最终使得的realloc 无操作,因为这两个尺寸凑够16个字节。

  1. malloc implementations do not typically operate on a byte granularity. Most of the ones I've seen round everything up to the nearest 16 bytes, since it makes accounting easier, and many users will need that alignment anyway. In your case, this would end up making the realloc a no-op, since both sizes round up to 16 bytes.

在最常见的多任务操作系统,应用程序访问,唯一的记忆就是自己 - 其他应用程序的内存在您的方式将永远不会得到。图书馆或其他线程分配的内存可能,虽然。

In most common multitasking operating systems, the only memory accessible to your application is its own -- other applications' memory will never get in your way. Memory allocated by libraries or other threads might, though.

这篇关于realloc的()和malloc函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆