top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Can I free() pointers allocated with new? Can I delete pointers allocated with malloc()

+2 votes
404 views
Can I free() pointers allocated with new? Can I delete pointers allocated with malloc()
posted Dec 23, 2014 by Alwaz

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

No!

It is perfectly legal, moral, and wholesome to use malloc() and delete in the same program, or to use new and free() in the same program.

But it is illegal, immoral, and despicable to call free() with a pointer allocated via new, or to call delete on a pointer allocated via malloc().

Beware! I occasionally get e-mail from people telling me that it works OK for them on machine X and compiler Y. Just because they don't see bad symptoms in a simple test case doesn't mean it won't crash in the field. Even if they know it won't crash on their particular compiler doesn't mean it will work safely on another compiler, another platform, or even another version of the same compiler.

Beware! Sometimes people say, "But I'm just working with an array of char." Nonetheless do not mix malloc() and delete on the same pointer, or new and free() on the same pointer! If you allocated via p = new char[n], you must use delete[] p; you must not use free(p). Or if you allocated via p = malloc(n), you must use free(p); you must not use delete[] p or delete p! Mixing these up could cause a catastrophic failure at runtime if the code was ported to a new machine, a new compiler, or even a new version of the same compiler.
You have been warned.

answer Dec 24, 2014 by Mohammed Hussain
Similar Questions
+4 votes

what is difference between new and malloc ??

+4 votes

Is there any alternate function is available?

+1 vote

I wanted to ask what is the GCC C++ equivalent implementation of Windows _ MyFirst and _MyLast vector pointers?

These give direct access to the vectors first and last element, but they are not present in the GCC implementation of the vector class.

...