new、delete、malloc、free 在堆栈上的使用区别 C++

 

int a[10] = { 0 } // 这是在栈中的
int b[10] = malloc(sizeof(int) * 10); // 这是在堆中的


malloc和free是函数,是标准库stdio中的
new和delete是关键字
new在堆上初始化一个对象的时候,会调用构造函数。 malloc不会。
delete使用之前,会调用对象的析构函数,再释放。  free不会调用析构。

 

#if 0  
//数组在堆中还是在栈中
int a[10] = { 0 } // 这是在栈中的
int b[10] = malloc(sizeof(int) * 10); // 这是在堆中的
malloc和free是函数,是标准库stdio中的
new和delete是关键字
new在堆上初始化一个对象的时候,会调用构造函数。 malloc不会。
delete使用之前,会调用对象的析构函数,再释放。  free不会调用析构。
#endif




#define _CRT_SECURE_NO_WARNINGS


#include <iostream>
using namespace std;

//在堆上  开辟内存空间


// 开辟一个字节
//C语言中
void test1()
{
	int* p = (int*)malloc(sizeof(int));
	*p = 10; //使用
	printf("C:%d", *p);
	printf("\n");
	if (p != NULL)
	{
		free(p);
		p = NULL;
	}
	
}

//C++语言中
void test2()
{
	int* p = new int;
	*p = 2; //使用
	cout << "C++:" << *p << endl;
	if (p != NULL)
	{
		delete p;
		p = NULL;
	}
	
}


// 开辟一个数组
//C语言中
void test3(int num)
{
	int* arr_p = (int*)malloc(sizeof(int)*num);
	
	//赋值使用
	for (int i = 0; i < num; i++)
	{
		arr_p[i] = i+1;
	}
	//打印
	for (int i = 0; i < num; i++)
	{
		printf("%d,",arr_p[i]);
	}
	printf("\n");
	//释放
	if (arr_p != NULL)
	{
		free(arr_p);
		arr_p = NULL;
	}
}

//C++语言中
void test4(int num)
{
	int* arr_p = new int[num];

	//赋值使用
	for (int i = 0; i < num; i++)
	{
		arr_p[i] = i + 1;
	}
	//打印
	for (int i = 0; i < num; i++)
	{
		cout << arr_p[i] << "," ;
	}
	cout << endl;
	//释放
	if (arr_p != NULL)
	{
		delete[] arr_p;
		arr_p = NULL;
	}
}


class Test
{
public:
	Test(int id,const char* name)
	{
		
		m_id = id;
		int len = strlen(name);
		m_name = (char*)malloc(len + 1);
		strcpy(m_name, name);	
		cout<<"Test()"<<endl;
	}
	void printT()
	{
		cout << "m_id=" << m_id << ",m_name=" << *m_name << endl;
	}
	~Test()
	{
		cout << "~Test()" << endl;
	}
private:
	int m_id;
	char *m_name;
};


void test5()
{
	Test* tp = (Test*)malloc(sizeof(Test));
	tp->printT(); //错误,因为tp指向的对象在创建的时候没有初始化值,没有可以打印的值
	if (tp != NULL)
	{
		free(tp);
		tp = NULL;
	}
}
void test6()
{
	Test* tp = new Test(10,"zhangsan");  //创建的时候,就调用了构造函数
	tp->printT();
	if (tp != NULL)
	{
		delete tp;
		tp = NULL;
	}
}



int main()
{
	test1();
	test2();
	test3(10);
	test4(10);
	cout << "--------" << endl;
	//test5();
	cout << "--------" << endl;
	test6();
	return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值