【C/C++】malloc和new的区别

本文探讨了C/C++中malloc和new的区别。malloc是C语言中的库函数,用于从堆中分配内存,需要配合free释放,而new是C++的运算符,自动分配适当内存并处理类型转换。malloc分配的内存需要手动计算大小,new则自动根据类型分配。文章还提到了realloc函数用于内存重新分配。

这俩其实都还没咋用过...好像学数据结构的时候用过然后就没用了..

先看看这俩都是啥

malloc库函数

malloc是定义在头文件 stdlib.h(C++里是cstdlib) 里的库函数

全称memory allocation 

void *malloc(size_t size)

分配所需的内存空间,并返回一个指向它的指针,参数size 是内存块的大小,以字节为单位。

malloc从堆里分配内存,函数返回的指针是指向堆里面的一块内存。

好像链表的时候用过

用一下试试..

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main(){

	char *str;
	str = (char*)malloc(10);
	//开一个内存size为10的char型...叫数组吗
	strcpy(str,"LiuYingjun");
	printf("String = %s,  Address = %p\n", str, str);
}

运行结果:

与之相对的有一个释放内存函数 void free(void *ptr)

然后一个重新分配函数void *realloc(void *ptr, size_t size)

new关键字

用法说明

// operator new example
#include <iostream>     // std::cout
#include <new>          // ::operator new

struct MyClass {
  int data[100];
  MyClass() {std::cout << "constructed [" << this << "]\n";}
};

int main () {

  std::cout << "1: ";
  MyClass * p1 = new MyClass;
      // allocates memory by calling: operator new (sizeof(MyClass))
      // and then constructs an object at the newly allocated space

  std::cout << "2: ";
  MyClass * p2 = new (std::nothrow) MyClass;
      // allocates memory by calling: operator new (sizeof(MyClass),std::nothrow)
      // and then constructs an object at the newly allocated space

  std::cout << "3: ";
  new (p2) MyClass;
      // does not allocate memory -- calls: operator new (sizeof(MyClass),p2)
      // but constructs an object at p2

  // Notice though that calling this function directly does not construct an object:
  std::cout << "4: ";
  MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
      // allocates memory by calling: operator new (sizeof(MyClass))
      // but does not call MyClass's constructor

  delete p1;
  delete p2;
  delete p3;

  return 0;
}

//http://www.cplusplus.com/reference/new/operator%20new/

 

区别:malloc是c的库函数,必须有调用库函数,声明头文件#include<stdlib.h>,new则是C++的运算符,它本身不是函数。

malloc分配内存之后必须用free函数释放内存,否则就会内存泄漏。

new自动分配多少的内存,malloc要自行计算。

比如说int *p=(*int)malloc(40); 并不是分配40个整型存储单元,而是40/sizeof(int)个整形存储单元。

而,int p=new int [40];是分配40个整型存储单元

参考:

1.菜鸟教程

2.浅谈malloc和new及他们的区别:这个写的无敌好!

https://blog.csdn.net/magic_world_wow/article/details/81370135?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值