c++中new分配的内存能否使用free释放?
大家讲道理
大家讲道理 2017-04-17 14:30:10
0
5
811

c++中new和free可以结合使用吗?

如下例,我new一个char数组,使用free释放,会不会造成生成什么安全问题?

代码可以编译运行,谢谢各位大神指点。

char * ch = new char[10];
for (int i = 0; i < 10; i++) 
{
    ch[i] = '0' + i;
}
free(ch);
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(5)
阿神

new and delete must be used in pairs and cannot be mixed with malloc|free. The way you write
may not be a problem for basic types, but once the constructor and destructor are involved No, it’s very important to develop habits.
And the standard library doesn’t seem to stipulate that new must be implemented using malloc, so things in new still need to be delete, not free

大家讲道理

It’s better to use delete

When using free, it is possible that the new object may not execute the destructor, which may cause a program error

迷茫

It is not recommended to use it this way. Use new/delete and malloc/free together

刘奇

Because the C++ standard does not require new memory allocation to be allocated by malloc, although some C++ implementations do this, but not all. Moreover, the new operator can be overloaded and custom memory allocation code can be written. In this case, it must not be free. In addition, for new class objects, free cannot be called because the destructor will not be called.

巴扎黑

First of all: the bottom layer of new and delete is implemented using malloc and free
Secondly: when it is a basic data type, delete and delete[] can be mixed
Using free can also release the space created by new, but new [] sometimes cannot be used
The key point is that it is best not to mix them

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!