Confusing with delete and free function in C++

Possible Duplicate:
What is the difference between new/delete and malloc/free?

class Foo
   {
    public:
     Foo() { x =  new int; } 
     ~Foo() { delete x; }
    private:
        int *x;
   };

  Foo *p = new Foo[10];
  free ( p );

I am getting confuse with the above code. Is there any problem about it?


When you call free() for an object allocated with new , its destructor is not called, so in this example you get memory leaks. Also, in this example you must use delete[] because memory is allocated with new[] .


Yep, there's a huge problem: new (and delete ) can be overridden by anyone for any type, and may or may not use malloc as the underlying allocator (really, it probably won't). Meanwhile, §20.4.6/4 of the C++03 standard says:

The function free() does not attempt to deallocate storage by calling ::operator delete() .

Meaning, any new invocation may allocate memory in any fashion, but free() will most likely not deallocate it correctly.


If you allocate an object with new, you must deallocate it with delete. free() frees blocks of memory allocated with malloc et al.

链接地址: http://www.djcxy.com/p/13770.html

上一篇: `malloc`和`new`之间的区别

下一篇: 用C ++中的删除和自由功能混淆