这俩其实都还没咋用过...好像学数据结构的时候用过然后就没用了..
先看看这俩都是啥
malloc库函数
malloc是定义在头文件 stdlib.h(C++里是cstdlib) 里的库函数
全称memory allocation
分配所需的内存空间,并返回一个指向它的指针,参数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及他们的区别:这个写的无敌好!
本文探讨了C/C++中malloc和new的区别。malloc是C语言中的库函数,用于从堆中分配内存,需要配合free释放,而new是C++的运算符,自动分配适当内存并处理类型转换。malloc分配的内存需要手动计算大小,new则自动根据类型分配。文章还提到了realloc函数用于内存重新分配。

3万+

被折叠的 条评论
为什么被折叠?



