且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在什么情况下我使用malloc vs新?

更新时间:2023-11-13 09:36:10

除非你***使用C,你应该永远不要使用malloc 。始终使用新。
如果你需要一个大块的数据,只需做一些事情:

  char * pBuffer = new char [1024] ; 

请注意这不正确:

  //这是不正确的 - 可能只删除一个元素,可能会损坏堆,或更糟... 
delete pBuffer;而是应该在删除数组时执行此操作:
$
$ p
  //删除数组中的所有项
delete [] pBuffer;

new关键字是C ++的做法,请确保您的类型具有构造函数。新关键字也更多类型安全,而malloc完全不是类型安全的。



如果您需要更改缓冲区大小,那么我认为使用 malloc 的数据。 new关键字没有类似于realloc的类似方式。 realloc函数可能能够更有效地扩展一块内存的大小。



值得一提的是,您不能混用new / free和malloc / delete。



在这个问题中无效。

  int * p_scalar = new int(5); //不创建5个元素,但初始化为5 
int * p_array = new int [5]; //创建5个元素


I see in C++ there are multiple ways to allocate and free data and I understand that when you call malloc you should call free and when you use the new operator you should pair with delete and it is a mistake to mix the two (e.g. Calling free() on something that was created with the new operator), but I'm not clear on when I should use malloc/ free and when I should use new/ delete in my real world programs.

If you're a C++ expert, please let me know any rules of thumb or conventions you follow in this regard.

Unless you are forced to use C, you should never use malloc. Always use new. If you need a big chunk of data just do something like:

char *pBuffer = new char[1024];

Be careful though this is not correct:

//This is incorrect - may delete only one element, may corrupt the heap, or worse...
delete pBuffer;

Instead you should do this when deleting an array of data:

//This deletes all items in the array
delete[] pBuffer;

The new keyword is the C++ way of doing it, and it will ensure that your type will have their constructor called. The new keyword is also more type safe whereas malloc is not typesafe at all.

The only way I could think that would be beneficial to use malloc would be if you needed to change the size of your buffer of data. The new keyword does not have an analogous way like realloc. The realloc function might be able to extend the size of a chunk of memory for you more efficiently.

It is worth mentioning that you cannot mix new/free and malloc/delete.

Note, some answers in this question are invalid.

int* p_scalar = new int(5);//Does not create 5 elements, but initializes to 5
int* p_array = new int[5];//Creates 5 elements