realloc函_realloc的()和malloc函数

本文探讨了C语言中realloc()函数的工作方式。当内存不足时,realloc()会尝试在堆区找到新的空间,复制原有内容并释放旧内存。然而,实际的内存分配通常以16字节对齐,这可能导致realloc()在此例中成为无效操作。在多任务操作系统中,应用程序只能访问自己的内存,不会与其他程序冲突。如果realloc()无法扩展内存,则会创建新块并释放旧块。
摘要由CSDN通过智能技术生成

Look at the code:

#include

#include

void main()

{

int *p;

p = malloc(6);

p = realloc(p, 10);

if (p == NULL)

{

printf("error");

exit(1);

}

}

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?

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?

解决方案

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.

HOWEVER:

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值