首页 > 其他分享 >malloc/free 和 new/delete的区别

malloc/free 和 new/delete的区别

时间:2023-09-17 23:14:38浏览次数:95  
标签:malloc free char printf Test new delete

class Test
{
public:
	char *a;
	Test() {
		this->a = (char *)malloc(10);//this->a表示对象自身的成员a
		strcpy_s(this->a, 10, "hello");
		printf("Test init\n");
	}
	~Test() {
		free(this->a);
		printf("Test deInit\n");
	}
};

int main()
{

	char *a = (char *)malloc(10);  //malloc不会做初始化
	Test *t = new Test; //new会自动调用构造函数进行初始化
	printf("a = %s\n", a);
	printf("t->a = %s\n", t->a);
	
	delete t;//new出来的对象需要手动delete,不会自动释放;同时delete会自动调用析构函数
	t = new Test;//new一个新对象
	return 0;
}

标签:malloc,free,char,printf,Test,new,delete
From: https://www.cnblogs.com/zhouhongyuan/p/17710066.html

相关文章

  • 动态内存分配(malloc,free)1
    使用动态内存开辟函数,可以创捷长度可变的数组大小,这样可以减少空间的浪费。在创建可变长度的数组时,其实在C99标准下,是可以直接创建的,例如linux下gcc编译器可以通过编译命令gcctest.c-std=c99,来实现。在vs下是不支持的,所以需要通过内存开辟函数来进行创建。在开辟空间的时候,有可能......
  • C语言实例_实现malloc与free函数完成内存管理
    一、malloc和free函数介绍在C语言中,malloc和free是用于动态内存管理的函数。(1)malloc函数malloc函数用于在堆(heap)中分配指定大小的内存空间,并返回一个指向该内存块的指针。原型如下:void*malloc(size_tsize);size参数表示要分配的内存块的大小,以字节为单位。函数返回一个指向分配内......
  • jfreechart中文无法显示的问题
    jfreechart是一个开源免费的Java图表工具。一个简单的入门例子:packageplot;importorg.jfree.chart.ChartFactory;importorg.jfree.chart.ChartFrame;importorg.jfree.chart.JFreeChart;importorg.jfree.chart.plot.PlotOrientation;importorg.jfree.data.category.Def......
  • C++new和delete运算符介绍
    内存管理运算符new、new[]、delete和delete[]也可以进行重载,其重载形式既可以是类的成员函数,也可以是全局函数。一般情况下,内建的内存管理运算符就够用了,只有在需要自己管理内存时才会重载。以成员函数的形式重载new运算符:void*className::operatornew(size_tsize){......
  • ES2023 Array new features All In One
    ES2023ArraynewfeaturesAllInOnechangeArraybycopyArray.toReversed()constnumbers=[1,2,3,4,5,6,7,8,9];constreversed=numbers.toReversed();console.log("reversed=",reversed);//reversed=[9,8,7,6,5,4,3,2,1]co......
  • API NEWS | 谷歌云中的GhostToken漏洞
    欢迎大家围观小阑精心整理的API安全最新资讯,在这里你能看到最专业、最前沿的API安全技术和产业资讯,我们提供关于全球API安全资讯与信息安全深度观察。本周,我们带来的分享如下:一篇关于谷歌云中的GhostToken漏洞的文章一篇关于Gartner对零信任的看法的文章一篇身份验证攻击威胁API安......
  • python: add more new row
    https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.htmldefappendDataToExcel(excelName,sheetName,data):"""EXCEL向后行插入数据:paramexcelName:EXCEL文件:paramsheetName:工作表名:paramdata:数据集合:ret......
  • freeswitch 编译安装问题汇总
    要编译,却没有configure文件,这是需要生成configure文件。按以下顺序执行命令即可生成configure文件。1.aclocal2.autoconf3.autoheader4.automake--add-missing5../configure6.make7.makeinstall项目https://github.com/kamalmostafa/minimodem就是这样的一个......
  • 视图模板____Freemarker入门demo
    //工程结构//代码类packagecom.freemarker.test;importjava.io.File;importjava.io.FileWriter;importjava.io.PrintWriter;importjava.util.HashMap;importjava.util.Map;importfreemarker.template.Configuration;importfreemarker.temp......
  • Eclipse自定义右键New菜单
    定制new菜单,点Window–>CustomizePerspective:选择new菜单所显示的快捷菜单......