C语言杂记-malloc与free

malloc与free:

为C语言提供的库函数,用来申请和释放指定大小的内存空间。使用示例如下:

1、malloc函数入参需要指定具体多少字节的内存空间,所以使用sizeof(int) * 5来计算总的内存字节数。

2、malloc函数返回申请到的地址首指针时,并不识别该指针的类型,即其原本返回为void*指针,因此需要加类型转换操作来指定该指针指向的数据类型。

3、释放时只需要free(p)就可以了。

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <numeric>

using namespace std;

int main()
{
	int* num = (int* )malloc(sizeof(int) * 5);
	for (int index = 0; index < 5; index++)
	{
		num[index] = index;
		cout << num[index] << endl;
	}

	free(num);
	system("pause");
	return 0;
}

new与delete:
为C++提供的运算符,用来申请和释放指定大小的内存空间。使用示例如下:
1、new在使用时只需要指定具体的数据类型以及多少个该数据的空间即可,不需要自己计算字节数。
2、如果是用new申请的动态数组,在释放时,需要使用delte[] p的形式来释放。
#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
#include <numeric>

using namespace std;

int main()
{
	int* num = new int[5];
	string* str = new string;
	*str = "hello";
	for (int index = 0; index < 5; index++)
	{
		num[index] = index;
		cout << num[index] << endl;
	}
	cout << *str << endl;

	delete[] num;
	delete str;
	system("pause");
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值