What will happen if I allocate memory using "new" and free it using "free" or allocate sing "calloc" and free it using "delete"?

Showing Answers 1 - 3 of 3 Answers

Yashwant S pinge

  • Mar 27th, 2006
 

It will give the resule of memory leak..

  Was this answer useful?  Yes

zdmytriv

  • Jan 24th, 2008
 

1. new and free - no constructor was called so you can get blocked memory(memory leak), but no error
2. calloc and delete - delete can be called to the object of the class, so you'll get and error

  Was this answer useful?  Yes

KishoreKNP

  • Dec 4th, 2009
 

new and free
When you use new operator for allocating the memory, it calls constructor by default, and when free the memory using "free" function, it won't call destructor of the class.
so if you are doing any important operations in destructor it wont be executed like delete the memory allocated in construtor or at any other function, stop the thread etc..,

calloc and delete

When you use calloc function for allocating the memory, it won't calls constructor and when free the memory using delete operator, it will call destructor of the class.
so if you are doing any important operations in the constructor it wont be called, for example starting a thread, allocate the memory for member varaibles etc..,


See the example below

#include <stdlib.h>
#include <iostream.h>
class CTest
{
public:
    CTest()
    {
        cout<<"nInside Ctor";
    }
    ~CTest()
    {
        cout<<"nInside Dtor";
    }
};
void main()
{
    cout<<"nnew and free";
    CTest *p = new CTest;
    free(p);
    cout<<"ncalloc and delete";
    CTest *p1 = (CTest*)calloc(1, sizeof(CTest));
    delete p1;
}

Output:
~~~~~
new and free
Inside Ctor
calloc and delete
Inside Dtor

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions