C/C++ 笔记(1)-- malloc 的工作原理

<span style="font-size:18px;">#include <stdio.h>
#include <unistd.h>
main()
{
	init *p1 = malloc(4);
	*p1 = 1;
	*(p1+1) = 1;
	*(p1+2) = 2;
	*(p1+3) = 3;
	*(p1+4) = 4;
	*(p1+5) = 5;</span>
<span style="font-size:18px;"></span><pre name="code" class="cpp"><span style="font-size:18px;"><span style="white-space:pre">	</span>*(p1+6) = 6;</span>
// free(p1)}

 
如果调用free 这句代码 就会导致程序报错,原因就在于malloc在分配内存的空间的时候 不光是分配内存空间 还会用12(不一定)个字节的数据来维护一个数据结构 

malloc 的工作原理:

malloc使用一个数据结构(链表)维护分配空间 

链表的构成:分配的空间/上一个空间数据/下一个空间数据

对malloc分配的空间不要越界访问 因为容易破坏后台维护结构,导致malloc/calloc/realloc/free 无法正常工作

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

<pre name="code" class="cpp">#include <stdio.h>
<span style="font-size:18px;">#include <unistd.h>
#include <stdlib.h>
int main()
{
	init *p1 = (int*)malloc(4);
	int* p2 = new int;
	int *p3 = (int*)malloc(4);
	int* p4 = new int;
	int* p5 = new int;
	int* p6 = new int;

	printf("%p\n",p1);
	printf("%p\n",p2);
	printf("%p\n",p3);
	printf("%p\n",p4);
	printf("%p\n",p5);
	printf("%p\n",p6);
		
	return 0;
}</span>


 

输出: 0x8429008

    0x8429018

    0x8429038

    0x8429038

            0x8429048

    0x8429058

C++ 的 new 与 malloc 的关系

new 的实现 使用的是malloc来实现的, 区别: new使用malloc后 还要初始化空间,基本类型,直接初始化成默认值。UDT类型,调用构造器 new 类型()

delete 调用free来实现的,区别在于:delete负责调用析构函数,然后调用free.

new 与new[]的区别:

new 只调用一个构造器初始化

new[ ]循环对每个区域调用构造器

-------------------------------------------------------------------------------------------------------------------------------------------------------------

定位分配运算符 new()

<pre name="code" class="cpp">#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <new>
int main()

	char p[20];
	init *p1 = new(p)int;
	return 0;
}


 

预先分配一个内存空间 自己来分配具体的空间来使用


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值