Home  >  Q&A  >  body text

c++中new分配的内存能否使用free释放?

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

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

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

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

reply all(5)I'll reply

  • 阿神

    阿神2017-04-17 14:32:10

    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

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 14:32:10

    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

    reply
    0
  • 迷茫

    迷茫2017-04-17 14:32:10

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

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 14:32:10

    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.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 14:32:10

    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

    reply
    0
  • Cancelreply